簡體   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