/**LDAP校验工具类--好像用到了单例模式
*/
public class LDAPVerifyUtils {
private static final Logger log = LoggerFactory.getLogger(LDAPVerifyUtils.class);
private static LDAPVerifyUtils util;
private String URL; //
private String BASEDN;
private String ROOT;
private String PASSWORD;
private String FACTORY;
private Control[] connCtls = null;
private LdapContext ctx; //Ldap上下文
//有参构造
private LDAPVerifyUtils (String root ,String password){
URL = PropertiesUtil.getAppContext("ldap.url");
BASEDN = PropertiesUtil.getAppContext("ldap.searchbase");
ROOT = root;
PASSWORD = password;
FACTORY= PropertiesUtil.getAppContext("ldap.ldapCtxFactory");
}
//获取实例
public static LDAPVerifyUtils getInstance(String root ,String password){
util = new LDAPVerifyUtils(root,password) ;
return util;
}
//启动连接
private void LDAP_connect(){
Hashtable<String ,String> env = new Hashtable<String ,String> ();
env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY): //javax.naming.Context
env.put(Context.PROVIDER_URL, URL+BASEDN);
env.put(Context.SECURITY_PRINCIPLE, "dahuatech\\"+ROOT);
env.put(Context.SECURITY_CREDENTIALS, PASSWORD);
env.put(Context.SECURITY_AUTHENTICATION, SIMPLE);
try{
ctx = new InitialLdapContext(env, connCtls);
log.info("连接至LDAP服务器成功! ");
}catch(javax.naming.AuthenticationException e){
log.error("连接至LDAP服务器失败"); //LDAP认证失败,用户名或密码错误
log.error(e.toString());
}catch(Exception e){
log.error("连接至LDAP服务器出错! ");
log.error(e.toString());
}
}
//关闭连接
public void closeContext(){
//关闭LdapContext
if(ctx != null ){
try{
ctx.close();
}catch(NamingException e){
log.error( e.toString() );
}
}
}
//获取用户DN(内方法,被认证方法调用)
private String getUserDN(String username){
String userDN = "";
try{
//1:打开连接
LDAP_connect();
SearchControls constraints = new SearchControls(); //查询控制项
constraints .setSearchScope(SearchControls .SUBTREE_SCOPE);
//2:从根目录开始查找
NamingEnumeration<SearchResult> en = ctx.search( "","(SAMAccountName=)"+username+")", constraints );
if( en == null || !en.hasMoreElements() ){ log.info("未找到该用户! ");} //枚举的判断空 用 hasMoreElements();
//3:获取用户DN,注意拼接BASEDN
while( en != null && en.hasMoreElements() ){
Object obj = en.nextElement();
if(obj instanceof SearchResult ){
SearchResult si = (SearchResult) obj;
userDN += si.getName();
userDN += "," + BASEDN;
}else{
}
}
}catch(Exception e){log.info("查找用户时发生异常...");}
return userDN;
}
//校验域用户名合法性
public void authenticate(String username, String password)throws Exception{
try{
//获取用户DN
String userDN = getUserDN(username);
if(userDN == null || "".equals( userDN.trim() )){ throw new Exception("用户名,密码不正确! ") ;}
ctx.addToEnvironment(Context.SECURITY_PRINCIPLE,userDN);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,password);
ctx.reconnect(conntls);
}finally{
//关闭相关连接
closeContext();
}
}
}//类尾
同学公司用的LDAP认证,我们公司也是的,但只是这个项目.学的时候学的是SpringSecurity. oh ,myGOD!