使用C#LdapConnection对象在LDAP中更改用户密码

时间:2014-08-22 19:19:56

标签: c# asp.net-mvc ldap

我正在使用C#客户端连接到OpenLDAP实例。

我需要验证用户是否输入了正确的旧密码。如果验证成功,我需要使用新密码更新其“userPassword”属性。

我不断获得DirectoryOperationException: A value in the request is invalid.以下是代码:

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);
        }

    }

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

在.NET framework 3.5及更高版本中,您可以使用System.DirectoryServices.AccountManagement,这将大大简化操作。
以下示例可能会解决您的问题

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();
    }
}

答案 1 :(得分:0)

我认为你正在使用的modtor中的最后一个参数是期望一个对象数组,而你只传递一个可能导致错误的值。

我使用此代替您的ModifyRequest行

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

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