ldap验证

ldap验证的工具类,具体的一些参数注释请参照相关文档。


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import java.util.Hashtable;

/**
* Ldap验证工具类,验证用户名和密码是否存在ldap服务器中。
*
* @author 张国明 [email protected]
* @version 2012-11-15 上午9:32
*/
public class LdapUtil {
private final Log log = LogFactory.getLog(getClass());
/**
* 连接url
*/
private static final String URL = "ldap://bj-dcd.zhanggmsoft.com:389";
/**
* 系统用户名
*/
private static final String PRINCIPAL = "t-bysystem";
/**
* 系统密码
*/
private static final String CREDENTIALS = "t-bysystem20120716";

private static LdapUtil instance = new LdapUtil();

private LdapUtil() {
}

public static LdapUtil getInstance() {
return instance;
}

/**
* 验证用户名和密码
*
* @param username 用户名
* @param password 密码
* @return 是否验证成功
* @throws Exception
*/
public boolean validateUser(String username, String password) throws Exception {
InitialDirContext initialContext = (InitialDirContext) getInitialContext();
try {
SearchControls sc = new SearchControls();
sc.setSearchScope(2);

NamingEnumeration iter = initialContext.search("dc=zhanggmsoft,dc=com", "(&(samaccountname=" + username + ")(objectclass=user))", sc);
if (iter.hasMoreElements()) {
SearchResult result = (SearchResult) iter.nextElement();
Attributes attributes = result.getAttributes();
Attribute att = attributes.get("distinguishedname");
String dn = (String) att.get();
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.PROVIDER_URL, URL);
env.put(Context.SECURITY_PRINCIPAL, dn);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.REFERRAL, "follow");
InitialDirContext initialContext1 = new InitialDirContext(env);
try {
initialContext1.search(dn, null);
} catch (Exception e) {
log.error(e);
return false;
} finally {
initialContext1.close();
}
} else {
return false;
}
return true;
} catch (Exception e) {
log.error(e);
return false;
} finally {
initialContext.close();
}
}

private InitialContext getInitialContext() throws Exception {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, URL);
env.put(Context.REFERRAL, "follow");
env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
return new InitialLdapContext(env, null);
}

public static void main(String[] args) throws Exception {
String username = "querenjie";
String password = "querenjie20120809";
boolean validate = getInstance().validateUser(username, password);
System.out.println("validate = " + validate);
}
}

你可能感兴趣的:(ldap验证)