LDAP user login (user authentication) and password change in Java

Source: Internet
Author: User

First, user authentication

Public string execute () {hashtable env = new hashtable (); string ldap_url =  "ldap://8.8.8.8:389";  // ldap access address env.put (Context.INITIAL_CONTEXT_ FACTORY, "Com.sun.jndi.ldap.LdapCtxFactory"); Env.put (Context.provider_url, ldap_url); Env.put ( context.security_authentication,  "simple"); Env.put (context.security_principal, username); Env.put ( Context.security_credentials, password); Try {dc = new initialdircontext (env);//  Initializes the context//  domain node string searchbase =  "dc=abc,dc=com"; string searchfilter =  "cn=" +username; Searchcontrols searchctls = new searchcontrols (); // create  Thesearchctls.setsearchscope (searchcontrols.subtree_scope);  // specify//set the properties of the query, based on the name of the login user oustring  returnedatts[] = {"distinguishedname"};//  Custom return Properties Searchctls.setreturningattributes ( Returnedatts); //  Set the Return property set//  Search ld based on the domain node, filter class, and search controller setThe AP Gets the result Namingenumeration<searchresult> entries = dc.search (Searchbase, searchfilter, SEARCHCTLS); Searchresult entry = entries.next (); Attributes attrs = entry.getattributes (); String disname = attrs.get ("distinguishedname"). ToString (); String[] disnamearray = disname.split (":"); String distinguishedname = disnamearray[1].trim ();//Set session         session.put ("distinguishedname",  distinguishedname);         //certified successful, Return to SUCCESSSYSTEM.OUT.PRINTLN ("certification Success");//This can be changed to an exception thrown. return  "Success";}  catch  (javax.naming.authenticationexception e)  {system.out.println ("Authentication failed");return  " Fail ";}  catch  (exception e)  {system.out.println ("Authentication error:"  + e);return  "fail";}}

Second, modify the user password

User authentication is relatively simple, a few lines of code, Microsoft is not allowed to change the password directly through Java (except C #), we need to use the certificate.

1. On the AD domain server, add the role Certificate Server, click here.

2. In IE, find your own certificate and export it by certificate, content--

3, export the certificate, need to import into a file, this file is called Cacerts. In this file, a tool Keytools.exe is also required. Position:

Cacerts:d:\soft\myeclipse2013\binary\com.sun.java.jdk.win32.x86_64_1.6.0.u43\jre\lib\security

Keytools:d:\soft\myeclipse2013\binary\com.sun.java.jdk.win32.x86_64_1.6.0.u43\bin

We need to import the exported certificate into the Cacerts via the Keytools tool, and the import method is to enter it in the DOS command:

D:\soft\myeclipse2013\binary\com.sun.java.jdk.win32.x86_64_1.6.0.u43\bin\keytool-import-keystore D:\soft\ Myeclipse2013\binary\com.sun.java.jdk.win32.x86_64_1.6.0.u43\jre\lib\security\cacerts-storepass Changeit- Keypass Changeit-alias Ca-file D:\ca\ca.cer

Copy To Dos, enter after the prompt whether to import, "Y" can be entered. All of this is done with our code:

Public void editpwd ()  throws namingexception {this.setnewpwd (New String (Decode ( NEWPWD)); This.setconfirmpwd (New string (Decode (CONFIRMPWD)));//ajax Request some code httpservletresponse  Response=servletactioncontext.getresponse (); Response.setcontenttype ("Text/html; charset=utf-8");   Map<String, Object> m = new HashMap<String, Object> ();// Verify that the password for the two-pass input is consistent if (!newpwd.equals (confirmpwd)) {        m.put ("success",  false)         m.put ("MSG",  "two times password input inconsistent, please re-enter. ");         jsonarray jsonarray = jsonarray.fromobject (M );        try {         Printwriter out = response.getwriter ();         Out.print (Jsonarray.tostring ()); &NBSP;&NBSP;&NBSP;&Nbsp;    } catch  (ioexception e)  {         e.printstacktrace (); some configuration of         }}//ladp hashtable  Env = new hashtable ();            string  adminName =  "Sja\\administrator";        string  adminpassword =  "[email protected]";         string  username = session.get ("distinguishedname"). ToString (). Replace ("%20",  " ");         String newPassword = newPwd;         string keystore = this.getclass (). GetResource (""). toString (). SUBSTRING ( 6). Replace ("%20",  " "). Replace ("/",  "\") + "Cacerts";         system.setproperty ("Javax.net.ssl.trustStore", KeyStore);         env.put (Context.initial_ Context_factory, "Com.sun.jndi.ldap.LdapCtxFactory");         env.put ( Context.security_authentication, "simple");            Env.put (Context.security_principal,adminname);            env.put (Context.security_credentials,adminpassword);            env.put (Context.security_protocol, "SSL");            String ldapURL =  "ldap://8.8.8.8:636";            env.put (Context.provider_url,ldapurl);            try {                printwriter&nbsP;out = response.getwriter ();             //Initialize Ldapcontext            ldapcontext  ctx = new initialldapcontext (env,null);             ModificationItem[] mods = new ModificationItem[1];             String newQuotedPassword =  "\" "  + newPassword +  "\" ";                byte[] newunicodepassword = newquotedpassword.getbytes ("UTF-16LE");                mods[0] =  New modificationitem (Dircontext.replace_attribute, new basicattribute ("UNICODEPWD",  Newunicodepassword)); &NBSP;&NBSP;&NBSP;&NBsp;           //  Change Password              ctx.modifyattributes (username, mods);                system.out.println ("Reset  password for:  " + username);                  ctx.close ();                m.put ("Success",  true);             jsonarray jsonarray = jsonarray.fromobject (m);             out.print (Jsonarray.tostring ());         }            catch  ( Namingexception e)  {&nbsP;              system.out.println (" problem resetting password:  " + e);             m.put ("Success",  false);             m.put ("msg",  "password does not meet the requirements or network connection error, try re-entering your password or contacting your administrator. ");             jsonarray jsonarray =  jsonarray.fromobject (m);             Printwriter out;            e.printstacktrace ();     try {out = response.getwriter (); Out.print (jsonArray.toString ());}  catch  (IOEXCEPTION&NBSP;E1)  {    // TODO Auto-generated  Catch block    e1.printstacktrace ();    }        }           }

Code writing is very rotten, just simple implementation of the function, I hope you make more bricks.

Java Password modification to the AD domain!! Certificate Import!!!

Java through LDAP operation ad Additions and deletions change query

LDAP user login (user authentication) and password change in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.