通过LDAP服务器验证用户身份

来源:互联网 发布:do it move it什么歌 编辑:程序博客网 时间:2024/05/17 07:18

最近做的项目中,登录时需要连接到远程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;
 }

原创粉丝点击