1 package com.portal.demo;
2
3 import java.util.Hashtable;
4
5 import javax.naming.AuthenticationException;
6 import javax.naming.Context;
7 import javax.naming.NamingException;
8 import javax.naming.directory.InitialDirContext;
9
10 public class Ady {
11 public static void main(String[] args) {
12 String username = "xxxx@sinsight.com";
13 String password = "xxxxx";
14 new Ady().ady(username, password);
15 }
16
17 /**
18 * 连接AD域,验证账号密码是否正确
19 *
20 * @param username
21 * @param password
22 * @throws NamingException
23 */
24 public void ady(String username, String password){
25 InitialDirContext ctx = null;
26
27 String host = "sinsight.com";
28 String post = "389";
29 Hashtable<String, String> hashtable = new Hashtable<String, String>();
30
31 hashtable.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
32 hashtable.put(Context.SECURITY_PRINCIPAL, username); // AD的用户名
33 hashtable.put(Context.SECURITY_CREDENTIALS, password); // AD的密码
34 hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
35 hashtable.put("com.sun.jndi.ldap.connect.timeout", "3000");// 连接超时设置为3秒
36 hashtable.put(Context.PROVIDER_URL, "ldap://" + host + ":" + post);
37 try {
38 ctx = new InitialDirContext(hashtable);// 初始化上下文
39 System.out.println("身份验证成功!");
40 } catch (AuthenticationException e) {
41 System.out.println("身份验证失败!");
42 e.printStackTrace();
43 } catch (javax.naming.CommunicationException e) {
44 System.out.println("AD域连接失败!");
45 e.printStackTrace();
46 } catch (Exception e) {
47 System.out.println("身份验证未知异常!");
48 e.printStackTrace();
49 } finally {
50 if (null != ctx) {
51 try {
52 ctx.close();
53 ctx = null;
54 } catch (Exception e) {
55 e.printStackTrace();
56 }
57 }
58 }
59
60 }
61 }