测试ldap连接

use*_*786 9 java spring ldap spring-security

我想验证用户输入的ldap设置.在设置页面上,用户输入ldap url,manager dn和password.我在此页面上有一个"测试设置"按钮,以便用户可以快速验证ldap连接.如何轻松快速地完成这项工作?

我们的应用程序使用spring安全性并在向其添加ldap身份验证的过程中.我是java和ldap的新手,所以非常感谢我指向正确的方向.

谢谢.

Mar*_*tör 11

根据给出的信息,很难说出你所知道的和你还不知道的.因此,我建议您在java.net LdapTemplate:Java Made Simple中使用这个有用的教程,跳过与您无关的章节(从2006年开始,但仍然可以).本文中引用的Spring LDAP现在是版本1.3.1.

如果您现在不想使用Spring LDAP,可以使用以下传统代码:

Map<String, String> env = new HashMap<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/dc=jayway,dc=se");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid="+ username +",ou=system"); // replace with user DN
env.put(Context.SECURITY_CREDENTIALS, password);

DirContext ctx;
try {
   ctx = new InitialDirContext(env);
} catch (NamingException e) {
   // handle
}
try {
   SearchControls controls = new SearchControls();
   controls.setSearchScope( SearchControls.SUBTREE_SCOPE);
   ctx.search( "", "(objectclass=person)", controls);
   // no need to process the results
} catch (NameNotFoundException e) {
   // The base context was not found.
   // Just clean up and exit.
} catch (NamingException e) {
   // exception handling
} finally {
   // close ctx or do Java 7 try-with-resources http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
}
Run Code Online (Sandbox Code Playgroud)


Nao*_*Bar 6

使用Spring LDAP身份验证测试LDAP连接:

即使用authenticate()方法:

ldapTemplate.authenticate(query, password);
Run Code Online (Sandbox Code Playgroud)

甚至更好,使用getContext()方法:

ldapTemplate.getContextSource().getContext(userDn, userPassword));
Run Code Online (Sandbox Code Playgroud)

捕获org.springframework.ldap.CommunicationException以检查连接是否成功.

完整的代码段应如下所示:

// Create the spring LdapTemplates; i.e. connections to the source and target ldaps:
try {
    // Note: I'm using the direct LdapTemplate initialization rather than with bean creation (Spring ldap supports both) 
    log.info("Connecting to LDAP " + sourceHost + ":" + sourcePort + "...");    
    LdapContextSource sourceLdapCtx = new LdapContextSource();
    sourceLdapCtx.setUrl("ldap://" + sourceHost + ":" + sourcePort + "/");
    sourceLdapCtx.setUserDn(sourceBindAccount);
    sourceLdapCtx.setPassword(sourcePassword);
    sourceLdapCtx.setDirObjectFactory(DefaultDirObjectFactory.class);
    sourceLdapCtx.afterPropertiesSet();
    sourceLdapTemplate = new LdapTemplate(sourceLdapCtx);
    // Authenticate:
    sourceLdapTemplate.getContextSource().getContext(sourceBindAccount, sourcePassword);
} catch (Exception e) {
    throw new Exception("Failed to connect to LDAP - " + e.getMessage(), e);
}
Run Code Online (Sandbox Code Playgroud)

注意:我使用的是spring LDAP 2.3.x版本:

<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)