0
votes

I am trying to change the User Account Property in Active Directory by using the UserPrincipal.

I have read that we have to use the special account which has the write access to the Active Directory rather than the current log on user. So, I created the special class to impersonate by using the Special Account. But I am still having the

System.UnauthorizedAccessException: General access denied error

at user.Save(ctx); line.

System.Security.Principal.WindowsImpersonationContext newUser = clsImpersonate.ImpersonateUser("ADUser", "ADPassword");

            if (newUser != null)
            {
                PrincipalContext ctx = blAD.GetAdminPrincipalContext();
                UserPrincipal user = blAD.GetUserPrincipal(this.SAMAccount);
                user.Enabled = false;
                user.Save(ctx);
                newUser.Undo();
            }

How can I achieve this requirement? Thanks.

3

3 Answers

0
votes

What permissions have been delegated to your special user? It needs to be able to write userAccountControl on the users in question.

0
votes

I wouldn't impersonate the account first off! Gain access through by passing the values through ad first.

For the real issue, look at the error:

  1. Get the principalContect.
  2. Get the userprincipal.
  3. Do what you want to do.
  4. Save it, why are u using undo? Delete the Undo().
0
votes

To access the Principle as another user, define your PrincipalContext with the credentials of the user and use that PrincipalContext when getting the UserPrincipal.

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.tld", "ADUser", "ADPassword");
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, this.SAMAccount);
    if (user != null) 
    {
        user.Enabled = false;
        user.Save();
    }

If you are still getting the UnauthorizedAccess Exception, it is likely because the account you are specifying does not have access to write the userAccountControl attribute on the user object in Active Directory/LDS.