Use java to connect to the AD domain and verify that the account and password are correct
In web projects, customers sometimes require us to use the ad domain for Identity confirmation, rather than a separate user management system. In fact, the customer only needs one account to access all office systems such as OA and CRM.
This is third-party verification. Generally, there are AD domains, Ldap, Radius, and email servers. The most commonly used field is the number of AD domains. Because the window system occupies a large proportion in China. It is easy to do.
This article explains how to use java to implement authentication for the AD domain. Okay. Check the Code directly:
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;/*** use java to connect to the AD domain and verify that the account and password are correct * @ author Herman. xiong * @ date 02:07:26 * @ version V3.0 * @ since jdk 1.6, tomcat 6.0 */public class AdTest {/*** use java to connect to the AD domain * @ author Herman. xiong * @ date 02:24:04 * @ return void * @ throws exception description * @ param host connects to the ip address of the AD Domain Server * @ param post AD Domain Server Port * @ param username * @ param password */public static void connect (String host, string post, String username, String password) {DirContext ctx = null; Hashtable
HashEnv = new Hashtable
(); HashEnv. put (Context. SECURITY_AUTHENTICATION, simple); // LDAP access security level (none, simple, strong) HashEnv. put (Context. SECURITY_PRINCIPAL, username); // The username HashEnv of AD. put (Context. SECURITY_CREDENTIALS, password); // the password of AD HashEnv. put (Context. INITIAL_CONTEXT_FACTORY, com. sun. jndi. ldap. ldapCtxFactory); // LDAP factory class HashEnv. put (com. sun. jndi. ldap. connect. timeout, 3000); // set connection timeout to 3 seconds HashEnv. put (Context. PROVIDER_URL, ldap: // + Host +: + post); // default port 389try {ctx = new InitialDirContext (HashEnv); // initialize the context System. out. println (authentication successful !);} Catch (AuthenticationException e) {System. out. println (authentication failed !); E. printStackTrace ();} catch (javax. naming. CommunicationException e) {System. out. println (AD domain Connection Failed !); E. printStackTrace ();} catch (Exception e) {System. out. println (unknown Exception in identity authentication !); 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 );}}
The code is over. Check the running effect: