Thursday, September 8, 2011

Code to Change the user's password store in the LDAP server

I did some prototype on changing the user's password, where the users and roles are store in the LDAP server.

The use case is, user logins into the system then he clicks on the change password link and that would display a form to change the password.
In this form, we capture the new password and send it to the method.

The following code can be used to change the password of a user.


public void changeUserPassword(String newPassword, String userName){
Hashtable env = new Hashtable();
String strAdminUser = "cn=Admin";
String strAdminPassword ="welcome";

try{
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, strAdminUser);
env.put(Context.SECURITY_CREDENTIALS, strAdminPassword);

//Get a reference to a directory context

DirContext ctx = new InitialDirContext(env);
System.out.println("getting directory context>"+ctx);
String user = "uid="+userName+",ou=people,ou=myrealm,dc=DefaultDomain";

NamingEnumeration ae = ctx.getAttributes(user).getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute)ae.next();
System.out.println("attribute "+attr.getID());
}

ModificationItem[] mods = new ModificationItem[1];
Attribute mod0 = new BasicAttribute("userpassword",newPassword);
mods[0] = new ModificationItem(ctx.REPLACE_ATTRIBUTE,mod0);

ctx.modifyAttributes(user,mods);
ctx.close();
}
catch (NamingException e) {

}
catch (Exception e)
{
}


}






No comments:

Post a Comment