Spring LDAP User Login UserPassword Authentication

Source: Internet
Author: User
Tags ldap relational database table

The Ldap password field is encrypted and requires password authentication when the user logs on or the user changes the password:

1. Self-Realization
/** * Integrated LDAP Login Verification * * @author WZC * @date December 11, 2017 pm 2:14:37 **/@Service Public classLdaplogin {/** * Create a Ldaptemplate Object * Connect LDAP*/@AutowiredPrivateldaptemplate ldaptemplate; PrivateContextsource Contextsource; /** * Login to verify LDAP * @param cn, Login username * @param pwd password * @return*/     PublicBoolean Loginldap (String cn, string pwd) {//based on CN, build DNString DN =Getdnforuser (CN); //Password VerificationBoolean result =authenticate (DN,PWD); returnresult; }         /** * @param usercn username * @param pwd password * @return based on username password*/@SuppressWarnings ("unchecked")         PublicBoolean Authenticate (String USERCN, string pwd) {DirContext CTX=NULL; System. out. println (USERCN +":"+pwd); Try {                     //Call the LDAP Authenticate method to verifyBoolean authenticate = Ldaptemplate.authenticate (USERCN,"(Objectclass=person)", PWD); returnauthenticate; } Catch(Exception e) {e.printstacktrace (); return false; } finally{ldaputils.closecontext (CTX); }                   }          /** * Build Entry Dn * @param cn * @return based on CN*/@SuppressWarnings ({"Unused","unchecked" })         Privatestring Getdnforuser (String cn) {List<String> results = Ldaptemplate.search ("","(& (Objectclass=person) (cn="+cn+"))",NewDnmapper ()); if(Results.size ()! =1) {                     Throw NewRuntimeException ("User not found or not unique"); } System. out. println (Results.Get(0)); returnResults.Get(0); }   }     /** * * Node DN mapping * * @author WZC * @date December 12, 2017 morning 11:21:09 **/     classDnmapper implements contextmapper{@Override PublicString Mapfromcontext (Object ctx) {dircontextadapter context=(Dircontextadapter) ctx; Name Name=Context.getdn (); String DN=name.tostring (); returnDN; }    }

If you want to summarize spring's LDAP (spring-developed open source jar for LDAP), you must start with LDAP.
Ldap:lightweight Directory Access Protocol, translation comes from a Lightweight directory accessing protocol.
It is based on the X.500 standard (X.500: The protocol that makes up the global Distributed Directory System), so abstract and basically understand that it is only a protocol, in the form of a directory (tree) to manage the source (user, user group, address Book, mail user, etc.). Some large companies choose to use LDAP to store users and their information.
So just like a database, LDAP has both client side and server side. Server side is used to store resources, client side to operate additions and deletions and other operations.

1. Ldap:schema

Directory in LDAP is organized by tree-directory Information tree (DIT)
Directory Information tree (DIT).
The DIT consists of (Entry) and the entries correspond to the records of tables in the relational database;
An entry is a collection of attribute-value pairs (attribute-value) with the distinguished name DN (distinguished name). (DN equivalent to primary key primary key in relational database table)
There's a lot more to learn about the basics of LDAP, such as client installation, data Model learning, and so on.

2. Spring LDAP

Spring LDAP is a Java-based LDAP client open Source Tool, primarily used for LDAP, and is implemented in a somewhat similar way to spring JdbcTemplate (which everyone is very familiar with ~)
Support Transaction (TRANSACTION)
Support for pooling (connection pooling)
Official documents and examples (important): http://docs.spring.io/spring-ldap/docs/2.1.0.RELEASE/reference/
Java documentation (important): http://docs.spring.io/spring-ldap/docs/2.1.0.RELEASE/apidocs/
GitHub (lots of examples): Https://github.com/spring-projects/spring-ldap

3. Core class: Ldaptemplate

This class is very similar to the implementation of Spring Jdbctemplate,jdbctemplate is to return the target list by passing in SQL statements and Rowmapper,query, or passing in SQL and parameters to execute the Update method. The advantage of JdbcTemplate is that it simplifies the code that connects to the database (which implements the LDAP attribute-to-object mapping, makes the code simpler and more elegant), and avoids some common mistakes. (This open source has been updated to the 4+ version, which can be seen in a wide range of applications).
The advantages are interlinked, and the advantage of Spring ldaptemplate is that it simplifies the code that interacts with LDAP (the traditional classes are described in the following:
http://docs.oracle.com/javase/7/docs/api/javax/naming/directory/package-summary.html) and avoids some common mistakes.

4. How to Understand Autherntication

To verify the identity of an LDAP entry (a bit similar to a username, password login), the idea of LDAP is to search through the DN to the target entry (for example, a company employee), then verify legitimacy through this entry and password.
Specific business such as: an employee to log into the company's website, enter his employee number and password. We are unable to get the user's password (the security limit) through the query in LDAP, then can only pass in the actual password, let the LDAP server side verify the legitimacy.
Ldaptemplate.authenticate (ldapquery query, String password);
There was a problem when using this method, as follows:
Validation always fails when calling Ldaptemplate.authenticate (always return false), and the document finds that if the LDAP connection has a connection pool, it is wrong to call the created connection to verify. The Authenticate verification process requires Contextsource to generate a connection by re-binding the incoming user name and password, which means that the connection connection used by this method cannot be the connection in the connection pool.
So we need a new Ldapcontextsource class and a Ldaptemplate class, and then through the Ldaptemplate class Setcontextsource (Contextsource contextsource) The contextsource that holds the user name password is passed in.
Note: After Contextsource is created, it is necessary to call the Afterpropertiesset () method to verify that all the necessary parameters have been set (specifically URLs, usernames, passwords, etc.) and that the actual contextsource will be instantiated after this method is executed. (especially in configurations outside of the spring context context, this method must be executed.)
This seems to be very abstract, the specific code is as follows:

1. Ldapcontextsource Contextsource =NewLdapcontextsource (); 2. Contextsource.seturl (URL); 3. Contextsource.setuserdn (USERDN); 4. Contextsource.setpassword (USERPWD); 5. contextsource.setpooled (false); 6. Contextsource.afterpropertiesset ();//Important7.8. Ldaptemplate template =Newldaptemplate (); 9. Template.setcontextsource (Contextsource); Ten. One. Boolean result = Template.authenticate (ldap_base_dn, filter, PWD);

5. Pooling
The Spring LDAP pool uses Apache Commons pool (http://commons.apache.org/proper/commons-pool/index.html)
6. Connect via SSL authentication mode
The company is using IBM's portal to install SSL, so the configuration of Tomcat is not very well understood. You can see the relevant information on the Stack-overflow.
In the more than one year of using spring LDAP, there was no problem that was too complex, and the product was also very stable after the launch. Generally speaking, because they are familiar with the JdbcTemplate thought somewhat similar, so the cost of learning is not high.

Spring LDAP User Login UserPassword authentication

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.