Java Program login authentication to user via LDAP

Source: Internet
Author: User

In the Nanjing Project last year, the client asked the user to log on to the other platform for authentication, then the client used the LDAP "database" Management method, later read Java has been encapsulated in LDAP, do not need to download other jar package can be implemented.

brain: "LDAP" is the abbreviation for "Lightweight Directory Access Protocol", which is called "Lightweight Directory Access Protocol", which can literally guess the database that should be stored in a tree shape, It is true that we read the data later. Several important parameters are included: Cn,dn,dc,ou. As for the meaning of this abbreviation word, interested can go to the encyclopedia or the official website of the brain, the following procedures will refer to these parameters, will also be a simple description.

Package Com.angma.mes.zbe.moudle.service.util;import Com.angma.mes.jagybarcode.manager.controller.plan.machine.machineshoptaskcreatecontroller;import Com.sun.org.apache.xerces.internal.impl.dv.util.base64;import Java.security.messagedigest;import Java.security.nosuchalgorithmexception;import Java.util.hashtable;import Java.util.logging.level;import Java.util.logging.logger;import Javax.naming.context;import Javax.naming.namingexception;import Javax.naming.directory.dircontext;import javax.naming.directory.initialdircontext;/** * User login authentication, LDAP cross-domain authentication, Update user via LDAP * * @author XLJ * @date 2015.07.10 */public class Ldaputil {private static dircontext ctx;//LDAP server port defaults to 38 9private static final String ldap_url = "ldap://127.0.0.1:389";//root confirms that the user organization is located in the private static final string LDAP_PRI based on this parameter Ncipal = "OU=CMA users,dc=changan-mazda,dc=com,dc=cn";//LDAP driver private static final String ldap_factory = " Com.sun.jndi.ldap.LdapCtxFactory ";p rivate static Logger Logger = Logger.getlogger (Ldaputil.class);Test ****/public static void Main (string[] args) {ldaputil.getlogincontext (); Ldaputil.adduserldap ("10000", "123456"); Ldaputil.updatepasswordldap ("10000", "1234567"); Ldaputil.deleteuserldap ("10000");} Authenticating the user by connecting to the LDAP server, returning the LDAP object public static DirContext Getlogincontext () {String account = "Zhangsan";//Impersonate the user name String pas Sword = "123456"; Analog password for (int i = 0; i < 5; i++) {//number of validations Hashtable env = new Hashtable (); Env.put (Context.security_authentication, "s Imple "); Env.put (context.security_credentials, password);//cn= The name of the organization structure, ou= the name of the organization structure under the rank position number Env.put ( Context.security_principal, "cn=" + account + ", ou=level0" + i + "xx," + Ldap_url); Env.put (context.initial_context_factor Y, Ldap_principal); Env.put (Context.provider_url, ldap_factory); try {//Connect LDAP for authentication ctx = new InitialDirContext (env); SYSTEM.OUT.PRINTLN ("Certified Success"); Logger.info ("" + account + "user at" "+ New SimpleDateFormat (" Yyyy-mm-dd HH:mm:ss "). Format ( New Date ()) + "Login system Success");} catch (Javax.naming.AuthenticationException e) {System.out.println ("Authentication failed");} catch (Namingexception err) {logger.info ("--------->>" + account + "User authentication failed" "+ i +" "Times"),} catch (Exception e) {Sy STEM.OUT.PRINTLN ("Authentication error:"); E.printstacktrace ();}} return CTX;} Validates the public static Boolean Verifysha (String ldappw, String inputpw) {//MessageDigest provides a message digest algorithm, such as MD5 or SHA, after the user and password are entered for the encryption algorithm , where LDAP uses sha-1messagedigest MD = messagedigest.getinstance ("SHA-1");//Remove the encrypted character if (Ldappw.startswith ("{Ssha}")) {LDAPPW = ldappw.substring (6);} else if (Ldappw.startswith ("{SHA}")) {LDAPPW = ldappw.substring (5);} Decode base64byte[] Ldappwbyte = Base64.decode (LDAPPW); byte[] shacode;byte[] salt;//The first 20 bits are SHA-1 encryption segments, and 20 bits are the random plaintext if when originally encrypted ( Ldappwbyte.length <=) {shacode = Ldappwbyte;salt = new Byte[0];} else {shacode = new Byte[20];salt = new BYTE[LDAPPW BYTE.LENGTH-20]; System.arraycopy (ldappwbyte, 0, Shacode, 0, 20); System.arraycopy (ldappwbyte, salt, 0, salt.length);} Add the user input password to the summary calculation information md.update (Inputpw.getbytes ());//Add the random plaintext to the digest calculation Information md.update (salt);//press Ssha to calculate the current user passwordbyte[] Inputpwbyte = Md.digest ();//Returns the check result return messagedigest.isequal (Shacode, inputpwbyte);} Add user public static Boolean Adduserldap (string account, String password) {Boolean success = false;try {CTX = Ldaputil.get LoginContext (); Basicattributes ATTRSBU = new Basicattributes (); BasicAttribute objclassset = new BasicAttribute ("objectclass"); Objclassset.add ("person"); Objclassset.add ("top"); O Bjclassset.add ("Organizationalperson"), Objclassset.add ("InetOrgPerson"); Attrsbu.put (Objclassset); Attrsbu.put (" SN ", account); Attrsbu.put (" UID ", account); Attrsbu.put (" UserPassword ", password); Ctx.createsubcontext (" cn= "+ Account + ", ou=people", ATTRSBU); Ctx.close (); return true;} catch (Namingexception ex) {try {if (CTX! = null) {Ctx.close ();}} catch (Namingexception namingexception) {namingexception . Printstacktrace ();} Logger.info ("--------->> Add user Failed");} return false;} Modify password public static Boolean Updatepasswordldap (string account, String password) {Boolean success = false;try {CTX = Ldapu Til.getloginContext (); modificationitem[] Modificationitem = new Modificationitem[1];modificationitem[0] = new Modificationitem ( Dircontext.replace_attribute, New BasicAttribute ("UserPassword", password)); Ctx.modifyattributes ("cn=" + account + ", Ou=people ", Modificationitem); Ctx.close (); return true;} catch (Namingexception ex) {try {if (CTX! = null) {Ctx.close ();}} catch (Namingexception namingexception) {namingexception . Printstacktrace ();} Logger.info ("--------->> Password change failed");} return success;} Delete User public static Boolean Deleteuserldap (String account) {try {ctx = Ldaputil.getlogincontext (); Ctx.destroysubcontext ("cn=" + account);} catch (Exception ex) {try {if (CTX! = null) {Ctx.close ();}} catch (Namingexception namingexception) {Namingexception.print StackTrace ();} Logger.info ("--------->> Delete user failed"); return false;} return true;} Close the LDAP server connection public static void Closectx () {try {ctx.close ()} catch (Namingexception ex) {logger.info ("--------->& Gt Shutdown LDAP connection failed ");}}}

Statement: The above tutorial for Bo Master original, if you need to reprint please indicate the source, thank you.

Java Program login authentication to user via LDAP

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.