【Java】LDAP AD域登录认证
项目遇到需要进行AD域认证的情况,先是使用了LdapTemplate,结果认证不了,换了下面的方式认证成功了
认证的时候,需要注意账号后面加上AD域服务器后缀!加上后缀!加上后缀!
public boolean ldapAuth(String username, String password){
boolean isLogin = false;
// log.info("登录账号:{},密码:{}", username, password);
// log.info("管理员账号:{}", LdapConfig.properties.getProperty("username"));
// log.info("LDAP地址:{}", LdapConfig.properties.getProperty("urls"));
Hashtable<String, String> env = new Hashtable();//实例化一个Env
username = username + "@xxxxx";
DirContext ctx = null;
env.put(Context.SECURITY_AUTHENTICATION, "simple");//LDAP访问安全级别(none,simple,strong),一种模式,这么写就行
env.put(Context.SECURITY_PRINCIPAL, username ); //用户名
env.put(Context.SECURITY_CREDENTIALS, password);//密码
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
env.put(Context.PROVIDER_URL, LdapConfig.properties.getProperty("urls"));//Url
try {
ctx = new InitialDirContext(env);// 初始化上下文
log.info("AD域验证成功!");
isLogin = true;
} catch (AuthenticationException e) {
log.error("AD域验证失败!", e);
} catch (javax.naming.CommunicationException e) {
log.error("AD域连接失败!", e);
} catch (Exception e) {
log.error("AD域验证未知异常!", e);
} finally{
if(null!=ctx){
try {
ctx.close();
ctx=null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return isLogin;
}