-
In EB projects, customers sometimes ask us to use the AD domain for identity verification, and no longer have to do another set of user management systems. In fact, the customer is as long as a set of accounts can access all OA,CRM and other office systems.
This is the third-party verification. Generally have ad domain, ldap,radius, mail server and so on. The most common is the number of ad domains. Because window System occupies a lot of land in the country. It is also very convenient to do.
I am writing this article, how to use Java to achieve the authentication of the ad domain. OK, look directly at the code:?
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 6667 |
package com.test;import java.util.Hashtable;import javax.naming.AuthenticationException;import javax.naming.Context;import javax.naming.directory.DirContext;import javax.naming.directory.InitialDirContext;/** * 使用java连接AD域,验证账号密码是否正确 * @author Herman.Xiong * @date 2014-12-23 下午02:07:26 * @version V3.0 * @since jdk 1.6,tomcat 6.0 */public class AdTest { /** * 使用java连接AD域 * @author Herman.Xiong * @date 2014-12-23 下午02:24:04 * @return void * @throws 异常说明 * @param host 连接AD域服务器的ip * @param post AD域服务器的端口 * @param username 用户名 * @param password 密码 */ 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(); } } } } public static void main(String[] args) { AdTest.connect(10.10.2.116, 389, herman@herman.com, 123456); }}</string,string></string,string> |
This concludes the code to see how it works:
-
-
Use Java to connect to the AD domain to verify that the account password is correct