JAVA implementation: Using sAMAccountName as login to authenticate __java through LDAP directory libraries

Source: Internet
Author: User
Tags ldap svn samaccountname

(reprint please indicate the source for this blog)

(2-2009 to 6-2009) to do a set of project development, tracking, management, multi-server synchronous backup system integration. The main combination of SVN, Apache, Tomcat, Bugzilla, SendMail, OpenSSL, LDAP, these open-source excellent software implemented under Ubuntu. It involves the Java EE Web Development, EMAIL, NDS application module configuration and combination, data encryption, project management process design, SVN data backup and recovery, and so on. And me and a couple of teammates are primarily responsible for developing a Web application that manages the user rights of the various libraries in SVN in detail.

Linux under the combination of these software is a master of Linux with two months time, step-by-step configuration, between the various problems encountered in the efforts of everyone, finally the whole system to build up.

Because the company has already built a very sophisticated LDAP directory library, LDAP directory library, like a communications record, which has been stored in the company's personnel basic information (such as name, mailbox, position, etc.). Here is a prerequisite: All company employees as users can log in to the Web application, after logging in, the system will be based on those SVN library for the user has open access, if so, to show the user. So we can make full use of this LDAP directory library, very convenient to manage the use of this Web application users.

Now, if you're not talking about the entire validation process, talk about how to match the information of the LDAP directory library when you log on, so you can authenticate by signing in. When matching an LDAP directory library record, you are required to provide the following information: LDAP directory library address, base DN, personal cn, login password. As an example of the following:

LDAP Directory store address : ldap://10.67.10.2:3268/
Benchmark DN:DC=CORP,DC=SB
A personal Cn:cn=xiaopeng DENG,OU=HR,DC=CN,DC=CORP,DC=SB
Login Password: 123456

sAMAccountName is an attribute of the personal CN node, such as the sAMAccountName value of the above personal cn: Xdeng. I named it shortname, or short name. It is very popular in foreign countries to use ShortName as a personal title in the company, including logins for various systems. Now this Web application will also use this sAMAccountName to log in as the login name. Check the Java Operations LDAP Library package, the solution is still some:

1, the user provides the sAMAccountName and the password, wants to login the system.

2, first use a known personal CN and its password to log in to the LDAP directory library. Once the login succeeds, an LDAP context class is returned here: Initialldapcontext.

3, using the method in this context class: Searchcontrols, you can return an enumeration class based on the search criteria string: Namingenumeration, at which point the search condition can specify the sAMAccountName value for the user input shortname.

4, if the search returns an enumeration class that has a value, it can get its CN value from that object. No, this user is not present

5, and then based on this CN value, and user-supplied password, the LDAP directory library login verification matching process.

The goal is very simple: first with a known CN and its password through the LDAP directory library authentication, and then you can find the user-supplied shortname of the corresponding CN, and finally use this CN and user-provided password authentication. The most important is to obtain the user ShortName corresponding CN.

The specific type of code to share out: (part of the changes after my eldest brother, more perfect, the eldest brother fierce.) )

Using a single state mode

The value of the Binddn,bindpassword variable in the code is the first known CN and its password, and the value is placed in the resource file.

 import Java.io.File; Import Java.io.FileInputStream; Import java.io.IOException; Import Java.net.URL; Import java.util.Hashtable; Import java.util.Properties; Import Javax.naming.Context; Import Javax.naming.NameClassPair; Import javax.naming.NamingEnumeration; Import javax.naming.NamingException; Import Javax.naming.directory.DirContext; Import Javax.naming.directory.InitialDirContext; Import Javax.naming.directory.SearchControls; Import Javax.naming.ldap.Control; Import Javax.naming.ldap.InitialLdapContext; Import Javax.naming.ldap.LdapContext; Import Javax.naming.ldap.SortControl; Import Org.apache.commons.logging.Log; Import Org.apache.commons.logging.LogFactory; Import com.util.Constant; /** * LDAP Connector seems like JDBC, supposed to interface with AD. * Use singleton prevent multi-instances. * */public class Ldapconnector {/** Logger to this class and subclasses/protected final log = Logfactory.getlog ( GetClass ()); private static Ldapconnector InstanCE Private String URL; Private String BaseDN; Private String Binddn; Private String Bindpassword; Private final hashtable<string, string> env = new hashtable<string, string> (); Private final control[] Sortconnctls = new Sortcontrol[1]; {try {sortconnctls[0] = new Sortcontrol ("sAMAccountName", control.critical);} catch (IOException ex) {}} private LDAP Connector () {try {URL fileUrl = GetClass (). getClassLoader (). getresource (Constant.file_ldap_config); File resource = new file (Fileurl.getfile ()); Properties Properties = new properties (); Properties.load (New FileInputStream (Resource)); url = properties.getproperty ("url"); BaseDN = Properties.getproperty ("BaseDN"); BINDDN = Properties.getproperty ("Binddn"); Bindpassword = Properties.getproperty ("Bindpassword"); Set up environment to creating initial context Env.put (Context.provider_url, URL + BaseDN); Env.put (Context.security_principal, BINDDN); Env.put (Context.security_credentials, Bindpassword); Env.put (context.secUrity_authentication, "simple"); Env.put ("Java.naming.batchsize", "50"); Env.put ("Com.sun.jndi.ldap.connect.timeout", "3000"); Env.put (Context.initial_context_factory, "com.sun.jndi.ldap.LdapCtxFactory"); Env.put ("Com.sun.jndi.ldap.connect.pool", "true"); The following pool parameters doesn ' t work//must setup as Java init parameters env.put ("Com.sun.jndi.ldap.connect.poo L.maxsize "," 3 "); Env.put ("Com.sun.jndi.ldap.connect.pool.prefsize", "1"); Env.put ("Com.sun.jndi.ldap.connect.pool.timeout", "300000"); Env.put ("Com.sun.jndi.ldap.connect.pool.initsize", "1"); Env.put ("Com.sun.jndi.ldap.connect.pool.authentication", "simple"); catch (Exception e) {//Ignore error E.printstacktrace ();}} public static Ldapconnector getinstance () {if (instance = null) instance = new Ldapconnector (); return instance;} publi C Boolean ValidateUser (string username, string password) {Boolean passed = false; Ldapcontext dircontext = null; try {//Create initial context DirContext = new InitialldapContext (env, SORTCONNCTLS); Dircontext.setrequestcontrols (SORTCONNCTLS); Searchcontrols controls = new Searchcontrols (); Controls.setsearchscope (Searchcontrols.subtree_scope); String filter = "(samaccountname=" + username + ")"; Namingenumeration<?> answer = Dircontext.search ("", filter, controls); String UserDN = null; while (Answer.hasmore ()) {UserDN = (Nameclasspair) answer.nextelement ()). GetName ();}//Set up environment for creating Initial context hashtable<string, string> env = new hashtable<string, string> (); Env.put (Context.provider_url, URL + BaseDN); Env.put (Context.security_principal, UserDN + "," + BaseDN); Env.put (context.security_credentials, password); Env.put (Context.security_authentication, "simple"); Env.put ("Com.sun.jndi.ldap.connect.timeout", "1000"); Env.put (Context.initial_context_factory, "com.sun.jndi.ldap.LdapCtxFactory"); Create initial context DirContext the context = new InitialDirContext (env); Passed = true; Context.close (); catch (NaMingexception e) {//Ignore error//E.printstacktrace ();} finally {if (DirContext!= null) {try {dircontext.close (); catch (Namingexception e) {e.printstacktrace ();}} return passed; } }

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.