通過LDAP服務器驗證用戶身份

最近做的項目中,登錄時需要連接到遠程LDAP服務器對用戶身份進行合法性驗證,並獲取登錄用戶權限等數據。下面是Java中訪問LDAP的核心代碼,供大家參考:

public boolean authenticateUserViaLdap(String username, String password)
   throws LogicException {
  Hashtable srchEnv = new Hashtable(11);

// 從ldap.properties配置文件中獲取LDAP服務器的一些屬性
  String ldapURL = PropertyUtils.getProperty("ldap.server.url",
    PROPFILEPATH);
  String ldapPort = PropertyUtils.getProperty("ldap.server.port",
    PROPFILEPATH);
  String authMode = PropertyUtils.getProperty("ldap.server.auth.mode",
    PROPFILEPATH);
  String searchBase = PropertyUtils.getProperty(
    "ldap.server.search.base", PROPFILEPATH);
  String authPrincipal = PropertyUtils.getProperty(
    "ldap.server.auth.principal", PROPFILEPATH);

  // replace the word [username] in authPrincipal with the user's name
  String resultAuthPrincipal = "";
  resultAuthPrincipal = authPrincipal.substring(0, authPrincipal
    .indexOf("[username]"))
    + username;
  if (authPrincipal.length() > (authPrincipal.indexOf("[username]") + "[username]"
    .length())) {
   resultAuthPrincipal += authPrincipal.substring(authPrincipal
     .indexOf("[username]")
     + "[username]".length());
  }

  logger.debug("security principal: " + resultAuthPrincipal);

  srchEnv.put(Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.ldap.LdapCtxFactory");
  srchEnv.put(Context.SECURITY_AUTHENTICATION, authMode);
  srchEnv.put(Context.SECURITY_PRINCIPAL, resultAuthPrincipal);
  srchEnv.put(Context.SECURITY_CREDENTIALS, password);
  srchEnv.put(Context.PROVIDER_URL, ldapURL + ":" + ldapPort);

  String[] returnAttribute = { "dn" };
  SearchControls srchControls = new SearchControls();
  srchControls.setReturningAttributes(returnAttribute);
  srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  String searchFilter = "(cn=" + username + ")";
  try {
   DirContext srchContext = new InitialDirContext(srchEnv);
   NamingEnumeration srchResponse = srchContext.search(searchBase,
     searchFilter, srchControls);
   String distName = srchResponse.nextElement().toString();

   logger.debug("user authentication successful.");

   return true;
  } catch (NamingException namEx) {
   logger.error("user authentication failed.");
   logger.error(namEx, namEx.fillInStackTrace());
  }
  return false;
 }

發佈了35 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章