繁体   English   中英

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

[英]How authenticate and search user in Active Directory using 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;
}

Spring LDAP参考手册中有一章是关于身份验证的单独一章 如果您有特定问题,请随时提出。

请注意,出于身份验证/授权的目的,您确实应该研究Spring Security (它反过来在底层使用Spring LDAP)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM