如何使用Spring Ldap在Active Directory中进行身份验证和搜索用户

时间:2016-05-12 10:13:11

标签: java spring spring-ldap

我使用 javax.naming.directory 编写了一些java代码,使用ldap对AD中的用户进行身份验证,该代码正常运行,正如我所期待的那样。但是我需要使用 Spring ldap api实现相同的代码。任何人都可以提供帮助。

初始化

private void setDefaultInitialContext() throws Exception
{
  LOG.debug("Setting default initail context");
  try
  {
    this.moLdapEnv.put(JAVA_NAMING_FACTORY_INITIAL, COM_SUN_JNDI_LDAP_LDAP_CTX_FACTORY);
    this.moLdapEnv.put(JAVA_NAMING_PROVIDER_URL, PropertiesReader.getLdapProperty(LDAP_URL) + ":" + PropertiesReader.getLdapProperty(LDAP_PORT));
    this.moLdapEnv.put(JAVA_NAMING_SECURITY_AUTHENTICATION, PropertiesReader.getLdapProperty(LDAP_AUTHTYPE));
    this.moLdapEnv.put(JAVA_NAMING_SECURITY_PRINCIPAL, PropertiesReader.getLdapProperty(LDAP_BIND_USER_DN));
    this.moLdapEnv.put(JAVA_NAMING_SECURITY_CREDENTIALS, PropertiesReader.getLdapProperty(LDAP_PASSWORD));
    this.moLdapContext = new InitialDirContext(this.moLdapEnv);
    LOG.debug("Default initail context is set");
  } catch (Exception exception)
  {
    LOG.error("An Exception occurred LdapDao setting default initial context :" + exception.getMessage(), exception);
    throw exception;
  }
}

身份验证:

public Boolean authenticate(String asUsername, String asUserPassword) throws Exception
{

  NamingEnumeration<SearchResult> results = null;
  Boolean liAuthResult = Boolean.FALSE;
  try
  {
    setDefaultInitialContext();
    SearchControls controls = new SearchControls();
    controls.setSearchScope(2);
    results = this.moLdapContext.search(PropertiesReader.getLdapProperty(LDAP_SEARCH_BASE_DN),
        "(&(objectclass=person)(sAMAccountName=" + asUsername + ")(memberOf=" + PropertiesReader.getLdapProperty(LDAP_GROUP_DN) + "))",
        controls);
    if (null != results && results.hasMore())
    {
      SearchResult searchResult = (SearchResult) results.next();
      if (null != searchResult)
      {
        moAttributes = searchResult.getAttributes();
        Attribute userDnAttr = moAttributes.get(DISTINGUISHED_NAME);
        String userDn = (String) userDnAttr.get();
        this.moLdapContext.close();
        this.moLdapEnv.put(JAVA_NAMING_SECURITY_PRINCIPAL, userDn);
        this.moLdapEnv.put(JAVA_NAMING_SECURITY_CREDENTIALS, asUserPassword);
        this.moLdapEnv.put(COM_SUN_JNDI_LDAP_CONNECT_POOL, FALSE);
        this.moLdapContext = new InitialDirContext(this.moLdapEnv);
        liAuthResult = Boolean.TRUE;
      }
      LOG.debug("User Authenticated successfully");
    }
  } catch (NamingException exception)
  {
    throw exception;
  } catch (Exception exception)
  {
    throw exception;
  } finally
  {
    closeAllResources(results);
  }
  return liAuthResult;
}

1 个答案:

答案 0 :(得分:0)

Spring LDAP参考手册中有一个separate chapter认证。如果您有具体问题,请随时提出。

请注意,出于身份验证/授权的目的,您应该查看Spring Security(后者又使用Spring LDAP)。