使用java连接AD域,验证账号密码是否正确
原文地址 https://www.cnblogs.com/haore147/p/5213728.html
public static void connect(String host,String post,String username,String password) {
DirContext ctx=null;
Hashtable<string,string> HashEnv = new Hashtable<string,string>();
HashEnv.put(Context.SECURITY_AUTHENTICATION, simple); // LDAP访问安全级别(none,simple,strong)
HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
HashEnv.put(Context.SECURITY_CREDENTIALS, password); //AD的密码
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,com.sun.jndi.ldap.LdapCtxFactory); // LDAP工厂类
HashEnv.put(com.sun.jndi.ldap.connect.timeout, 3000);//连接超时设置为3秒
HashEnv.put(Context.PROVIDER_URL, ldap:// + host + : + post);// 默认端口389
try {
ctx = new InitialDirContext(HashEnv);// 初始化上下文
System.out.println(身份验证成功!);//要特别注意,如果输入的密码为空,那么仍然会验证成功,在这里是不会报错的,很诡异的设计!!!!
} catch (AuthenticationException e) {
System.out.println(身份验证失败!);
e.printStackTrace();
} catch (javax.naming.CommunicationException e) {
System.out.println(AD域连接失败!);
e.printStackTrace();
} catch (Exception e) {
System.out.println(身份验证未知异常!);
e.printStackTrace();
} finally{
if(null!=ctx){
try {
ctx.close();
ctx=null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
要特别注意:要特别注意,如果输入的密码为空,那么仍然会验证成功,在这里是不会报错的,很诡异的设计!!!!