Program to validate a user against LDAP for login Authentication
Hi All ,
I have a very basic issue in LDAP . I am using OPEN DS as my LDAP Server and JNDI API to access LDAP Server for authorization.
After creating a new user in Open DS, I created an html with username & password as textfield. Then I created a servlet which connected succesfully to LDAP Server. However, I am getting the password from LDAP Server for the current user in encrypted / digested format and hence my authorization always fails.
This is my code:
==============
Code :
package com.login.servlet;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.ldap.InitialLdapContext;
..
public class LoginServlet extends HTTPServlet{
private static DirContext createLdapContext() throws NamingException {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://172.30.91.123:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=Directory Manager");
env.put(Context.SECURITY_CREDENTIALS, "opends");
return new InitialLdapContext(env, null);
}
public void validateUser(HttpServletRequest request, SessionVO sessionVO) {
try {
String un=request.getParameter("username");
String pwd = request.getParameter("password");
DirContext dirContext = createLdapContext();
Attributes attrs = dirContext.getAttributes("uid="un",ou=People,dc=example,dc=com");
String actualPwd = attrs.get("userPassword").toString();
if(pwd.equals(actualpwd)){
System.out.println("Password correct");
}else {
System.out.println("Password worng");
// I am getting this message always for both correct and incorrect password.
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
=======================================
I beleive that the authentication of the user should happen against the directory server and not inside the application like done in the above code .
Either way I am stuck without a sample to proceed.
My question is, how to write a program using JNDI API to authorize an user from LDAP Server for a login Screen?
Thanks in Advance !
Re: Program to validate a user against LDAP for login Authentication
Good morning,
As I see it you either need to call an authorize method on the LDAP interface which just takes care of all this for you or you will have to hash the user password with the same hash algorithm used by the LDAP service and then compare them.
// Json