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

本文介绍了一个项目中如何使用Java连接到远程LDAP服务器,对用户身份进行验证的实现过程。通过读取配置文件获取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;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值