Ishara Madawa
Ishara Madawa

Reputation: 1612

UnauthorizedAccessException: Access is denied when changing AD password

I am try to write C# code for update Domain User Password in Server 2012. I'm using following code according to this Stack Overflow answer

using (var context = new PrincipalContext(ContextType.Domain, "test.com"))
{
    using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
    {
        user.SetPassword(newPassword);
        //user.ChangePassword(oldPassword, newPassword);
        user.Save();
    }
}

in getting following exception when running code

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

I also disabled password policy. Any advice?

Upvotes: 1

Views: 5029

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40858

The account your code is running under doesn't have permissions. You have two options:

  1. Run your program under credentials that do have the right permissions, or
  2. Use a different constructor for PrincipalContext and pass a username and password that has permissions to set the password:
var context = new PrincipalContext(ContextType.Domain, "test.com", "domain\username", "password");

Upvotes: 5

Related Questions