开发者

Change an Active Directory password [duplicate]

开发者 https://www.devze.com 2023-04-11 17:59 出处:网络
This question already has answers here: How to programmatically change Active Directory password (6 answers)
This question already has answers here: How to programmatically change Active Directory password (6 answers) Closed 4 years ago.

At first, please forgive my English, it is not my mother tongue.

I'm working on a web platform that manages Active Directory. I can create, delete and edit a 开发者_JS百科group, user, OU, and so on.

When a connected user wants to change his own password with the platform, it fails.

It comes from DirectoryEntry.Invoke.

I used the DirectoryServices.DirectoryEntry:

directoryEntry.Invoke("SetPassword", password);
directoryEntry.Commit();

So I tried System.DirectoryServices.AccountManagement:

PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Username);
user.SetPassword(password_);
user.Save();

Different way, same problem.

It only fails when a user tries to edit his own password.

Any help would be grateful.


Try this code. It works for me,

public void ChangeMyPassword(string domainName, string userName, string currentPassword, string newPassword)
{
    try
    {
        string ldapPath = "LDAP://192.168.1.xx";
        DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainName + "\\" + userName, currentPassword);
        if (directionEntry != null)

        {
            DirectorySearcher search = new DirectorySearcher(directionEntry);
            search.Filter = "(SAMAccountName=" + userName + ")";
            SearchResult result = search.FindOne();
            if (result != null)
            {
                DirectoryEntry userEntry = result.GetDirectoryEntry();
                if (userEntry != null)
                {
                    userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
                    userEntry.CommitChanges();
                }
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


As Paolo notes, you can't call Reset Password without extra privileges. To call ChangePassword, you need to supply the previous password like this:

directoryEntry.Invoke("ChangePassword", oldPassword, newPassword); 
directoryEntry.Commit(); 


This is a Windows restriction: a user cannot reset his own password, i.e. change the password without providing the old one.

You can only change your own password, i.e. provide old password and new password.
Try using the ChangePassword method instead.


Change Password requires user's old password to set new password and Reset password permission requires to the person who resets the password.With AD's default permissions, only Administrators and Account Operators can reset passwords.

0

精彩评论

暂无评论...
验证码 换一张
取 消