0
votes

I have the following code that changes an user password in LDAP. It works if I use the user's CN, but I have no idea of what should I do to do it work with the sAMA.

    public static void main(String[] args) {

    Properties prop = new Properties();
    prop.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    prop.put(Context.SECURITY_AUTHENTICATION, "simple");
    prop.put(Context.SECURITY_PRINCIPAL, "[email protected]");
    prop.put(Context.SECURITY_CREDENTIALS, "ifpr2018");
    prop.put(Context.SECURITY_PROTOCOL, "ADSecurityProtocol");
    prop.put(Context.PROVIDER_URL, "ldap://localhost/OU=Group,DC=ifjac,DC=redelocal");

    try {
        LdapContext ctx = new InitialLdapContext(prop, null);
        String oldPassword = "old";
        String newPassword = "new";
        ModificationItem[] mods = new ModificationItem[2];

        String oldQuotedPassword = "\"" + oldPassword + "\"";
        byte[] oldUnicodePassword = oldQuotedPassword.getBytes("UTF-16LE");
        String newQuotedPassword = "\"" + newPassword + "\"";
        byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");

        mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
                new BasicAttribute("unicodePwd", oldUnicodePassword));
        mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
                new BasicAttribute("unicodePwd", newUnicodePassword));


        String theUserName = "CN=user, OU=Users";

        ctx.modifyAttributes(theUserName, mods);
        System.out.println("Changed Password for successfully");
        ctx.close();
    } catch (Exception e) {
        System.err.println("Problem changing password: " + e);
    }
}
1

1 Answers

1
votes

You need the find the user in AD using the sAMAccountName first and take the DN out of the search result and put it into the theUserName variable.

Create a filter that looks like this:

(sAMAccountName={theSamAccountName})

Then use it to search the directory.