import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class AdTest {
public static void main(String[] args) {
String userName = "jyl";//AD域认证,用户的登录UserName
String password = "xxx";//AD域认证,用户的登录PassWord
String host = "xxx";//AD域IP,必须填写正确 已经加入的域
String domain = "xxx";//域名后缀
String port = "389"; //端口,一般默认389
String user = userName.indexOf(domain) > 0 ? userName : userName
+ domain;
connect(host, port, user, password);
}
public static void connect(String host, String port, 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 + ":" + port);// 默认端口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();
}
}
}
}
}```
网友评论