How do I use an EJB to handle simple authentication to an LDAP directory?

Nicholas Whitehead

There are code samples in Sun's JNDI tutorial that explain how to perform LDAP authentication through JNDI.

My recommendation would be to create a session bean that acquires an LDAP /JNDI context in the setSession() method. A subsequent call to authenticate would pass in a user and password. The following code shows how to authenticate the passed values:

env.put(Context.InitialContextFactory, "com.sun.jndi.ldap.LdapCtxFactory"); // I added this line myself
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");
// Create the initial context
DirContext ctx = new InitialDirContext(env);

A failure in authentication will cause this code to throw a javax.naming.AuthenticationException

You may want to store the actual LDAP tree that contains the users you are authenitcating so youi can dynamically set it without recoding, so the actual code may look like this if you store the LDAP tree name in JNDI as "myUserLDAPTree" (ou=NewHires, o=JNDITutorial):

env.put(Context.InitialContextFactory, "com.sun.jndi.ldap.LdapCtxFactory"); // I added this line myself
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=" + passedUserName + "," + (String)new InitialContext().lookup("myUserLDAPTree"));
env.put(Context.SECURITY_CREDENTIALS, passedPassword);
// Create the initial context
DirContext ctx = new InitialDirContext(env);

The simply return a true, or a false if a javax.naming.AuthenticationException is thrown.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact