Create user Active Directory: Exception has been thrown by the target of an invocation. thrown at UserPrincipal

0

When I try to create user in active directory I get an exception:

(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) error

Code:

UserPrincipal userPrincipal = new UserPrincipal(principalContext);
userPrincipal.SamAccountName = serviceAccount.SAMAccountName;
userPrincipal.PasswordNeverExpires = serviceAccount.PasswordNeverExpires;
userPrincipal.SetPassword(passwordOfAccount);
userPrincipal.Enabled = serviceAccount.Enabled;

// Creates the account
try
{
    userPrincipal.Save();
}
catch (Exception e)
{
    return false;
}
return true;

I get the error at

userPrincipal.Save();
active-directory
userprincipal
asked on Stack Overflow Jul 29, 2019 by saurav7044 • edited Jul 29, 2019 by marc_s

1 Answer

0

E_ACCESSDENIED means that the account you are using to do this does not have permissions to do what you're doing.

You don't show your code where you create your PrincipalContext object, but if you did not give it a username and password, then it is using whatever credentials the process is running under, which sounds like it's not good enough.

You need to use one of the PrincipalContext constructors that lets you provide a username and password. For example:

var principalContext = new PrincipalContext(
                            ContextType.Domain,
                            "example.com",
                            "ou=Users,dc=example,dc=com",
                            "username",
                            "password"
                       );

Where "example.com" is your domain name, ""ou=Users,dc=example,dc=com"" is the OU where you want to create the accounts, and "username" and "password" belong to an account that has permissions to create user accounts in that OU.

answered on Stack Overflow Jul 29, 2019 by Gabriel Luci

User contributions licensed under CC BY-SA 3.0