简体   繁体   中英

Changing user password in LDAP using C# LdapConnection Object

I am using a C# client to connect to an OpenLDAP instance.

I need to verify that the user has input the correct old password. If that verification succeeds, I need to update their "userPassword" attribute with a new password.

I keep getting DirectoryOperationException: A value in the request is invalid. Here's the code:

public static void UpdateUserPassword(ref UserProfile user, string oldPassword, string newPassword) {

        string connAccountName = ControllerHelper.GetProperty("VSP_SECURITY_PRINCIPAL", true);
        string connAccountPassword = ControllerHelper.GetProperty("VSP_SECURITY_CREDENTIALS", true);

        int myConnectionId;
        LdapConnection ldapConnection;
        lock (_sConnectionTable.SyncRoot) {
            myConnectionId = _getFirstOpenConnectionId();
            ldapConnection = _getConnectionFromPool(ref myConnectionId);//check for null
        }


        try {

            /*Here is where I try to validate the user's old password*/
            ldapConnection.Bind(new NetworkCredential(user.dnName, oldPassword));

            ModifyRequest request = new ModifyRequest(
                    user.dnName,
                    DirectoryAttributeOperation.Replace,
                    "userPassword",
                    newPassword

                );

            ModifyResponse modResponse = (ModifyResponse)ldapConnection.SendRequest(request);

            user.state.successMsg = "Yay it worked!";

        }
        catch (Exception e) {
            user.state.errorMsg = e.Message;

        }
        finally {
            _releaseConnectionToPool(myConnectionId);
        }

    }

Any help would be appreciated. Thanks!

in .NET framework 3.5 and higher you can use System.DirectoryServices.AccountManagement which will greatly simplify things.
the example below might solve your problem

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
        user.ChangePassword(oldPassword, newPassword);
        user.UnlockAccount();
    }
}

I think the last param of ModifyRequest in the ctor you are using expecting an object array and you are only passing a single value which is probably causing your error.

I'd use this instead of your ModifyRequest line

DirectoryAttributeModification modifyUserPassword = new DirectoryAttributeModification();
modifyUserPassword.Operation = DirectoryAttributeOperation.Replace;
modifyUserPassword.Name = "userPassword";
modifyUserPassword.Add(newPassword);

ModifyRequest modifyRequest = new ModifyRequest(user.dnName, modifyUserPassword);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM