Thursday, 16 September 2010

Retrieving password, using spring-ldap

Consider following code snippet:
public class PasswordContextMapper extends AbstractContextMapper {
public static final String UID = "uid";
public static final String PASSWORD = "userPassword";
public static final String[] LDAP_ATTRIBUTES = { UID, PASSWORD };

@Override
protected Password doMapFromContext(DirContextOperations ctx) {
final Password p = new Password();
p.setPassword(ctx.getStringAttribute(PASSWORD));
p.setUid(ctx.getStringAttribute(UID));
return p;
}
}

Looks ok? Think again. There's one pitfall with password retrieval from LDAP. Although different LDAP viewers show password as hashed text, it's really an array of bytes. This code throws something like
[B cannot be cast to java.lang.String
It actually says that "Cannot cast from array of bytes to String" ('[' shows that object is array of something). Solution is trivial. Change ctx.getStringAttribute(PASSWORD) to ctx.getObjectAttribute(PASSWORD).toString();