springbootldap与嵌入式ldap集成测试

dy1byipe  于 2021-07-15  发布在  Java
关注(0)|答案(0)|浏览(356)

我们和jhipster有一个微服务架构。其中一个模块是uaa服务。我们使用ldap而不是用户身份验证的spring安全特性。所以我编写了这个ldapservice,它是从userdetailservice使用的。

@Service
public class LdapService {

    private final ApplicationContext applicationContext;

    @Value("${ldap.url}")
    private String ldapUrl;

    @Value("${ldap.baseDn}")
    private String baseDn;

    @Value("${ldap.userdn}")
    private String userDn;

    @Value("${ldap.password}")
    private String password;

    public LdapService(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public Optional<User> authenticate(String login, String userPassword) {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(ldapUrl);
        contextSource.setBase(baseDn);
        contextSource.setUserDn(userDn);
        contextSource.setPassword(password);
        contextSource.afterPropertiesSet();

        LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
        try {
            ldapTemplate.afterPropertiesSet();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Perform the authentication.
        Filter filter = new EqualsFilter("cn", login);
        boolean authenticated = ldapTemplate.authenticate("", filter.encode(), userPassword);

        if (authenticated) {
            // Search for user information
            List<User> searchResult = ldapTemplate.search("", filter.encode(), (AttributesMapper<User>) attributes -> {
                User u = new User();
                u.setLogin((String) attributes.get("cn").get());
                u.setEmail((String) attributes.get("mail").get());
                u.setLastName((String) attributes.get("sn").get());
                u.setFirstName((String) attributes.get("givenname").get());
                u.setActivated(true);
                u.setPassword(((PasswordEncoder) applicationContext.getBean("passwordEncoder")).encode("changeit"));
                return u;
            });
            return searchResult.stream().findFirst();
        }
        return Optional.empty();
    }

如果用户在ldap中被成功授权,那么该用户将被持久化到db中。所有这些都有效。
为了测试这一点,我正在编写一个集成测试,但我不想使用“生产”ldap。我的意图是使用spring的嵌入式ldap。所以我配置了一个ldif文件和测试资源的application.yml。如果我运行测试,使用ldaptemplate的搜索会得到“connection densed”。有人知道我做错了什么吗?
应用程序.yml

spring:
  ldap:
    embedded:
      base-dn: dc=asb,dc=com
    credential:
      username: admin
      password: secret
    ldif: classpath:ldap-server.ldif
    port: 123
    validation:
      enabled: false

ldap:
  url: ldap://localhost:123
  userDn: cn=admin,dc=asb,dc=com
  baseDn: dc=asb,dc=com
  password: secret

ldapserviceit.java文件

@SpringBootTest(classes = UaaServiceApp.class)
@Transactional
public class LdapServiceIT {

    @Autowired
    private LdapService ldapService;

    @Test
    @Transactional
    public void basic_user_authentication() {
        Optional<User> authenticatedUser = ldapService.authenticate("beeblebroxz", "hearthofgold");
        assertThat(authenticatedUser.isPresent(), is(true));
    }

}

堆栈跟踪

org.springframework.ldap.CommunicationException: localhost:123; nested exception is javax.naming.CommunicationException: localhost:123 [Root exception is java.net.ConnectException: Connection refused: connect]

    at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:108)
    at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:355)
    at org.springframework.ldap.core.support.AbstractContextSource.doGetContext(AbstractContextSource.java:139)
    at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:158)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:357)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578)
    at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1441)
    at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1426)
    at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1369)
    at uaa.security.LdapService.authenticate(LdapService.java:57)
    at 
uaa.security.LdapServiceIT.basic_user_authentication(LdapServiceIT.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:532)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:108)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: javax.naming.CommunicationException: localhost:123 [Root exception is java.net.ConnectException: Connection refused: connect]
    at com.sun.jndi.ldap.Connection.<init>(Connection.java:243)
    at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:137)
    at com.sun.jndi.ldap.LdapClient.getInstance(LdapClient.java:1615)
    at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2849)
    at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:347)
    at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxFromUrl(LdapCtxFactory.java:225)
    at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:189)
    at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:243)
    at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:154)
    at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:84)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
    at javax.naming.InitialContext.init(InitialContext.java:244)
    at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:154)
    at org.springframework.ldap.core.support.LdapContextSource.getDirContextInstance(LdapContextSource.java:42)
    at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:343)
    ... 50 more
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:607)
    at java.net.Socket.connect(Socket.java:556)
    at java.net.Socket.<init>(Socket.java:452)
    at java.net.Socket.<init>(Socket.java:229)
    at com.sun.jndi.ldap.Connection.createSocket(Connection.java:380)
    at com.sun.jndi.ldap.Connection.<init>(Connection.java:220)
    ... 65 more

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题