您的位置:首页 > 其它

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

2009-03-18 23:05 501 查看
最近做的项目中,登录时需要连接到远程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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐