apan23
apan23

Reputation: 11

Access denied when calling UserPrincipal methods

I'm attempting to access Active Directory on an on-premise server from a web app running on an Azure App Service over a site to site VPN using the System.DirectoryServices.AccountManagement package. The following works as expected and does disable the user account as intended:

adContext = new PrincipalContext(ContextType.Domain, "10.0.0.1", c.Username, c.Password);

u = UserPrincipal.FindByIdentity(adContext, user.UserPrincipalName;

u.Enabled = false;
u.Save();

However when I try the following I get an error

System.UnauthorizedAccessException: Access is denied. (0x80070005 (E_ACCESSDENIED))

on the SetPassword method:

adContext = new PrincipalContext(ContextType.Domain, "10.0.0.1", c.Username, c.Password);

u = UserPrincipal.FindByIdentity(adContext, user.UserPrincipalName;

u.SetPassword(response.Replace(" ", "-"));

I'm fairly sure this isn't an issue with my credentials or connection to the server as the command to Enable/Disable works fine and the program executes properly when run directly from Visual Studio. The AD credentials supplied in the PrincipalContext command have Domain Admin privileges for the purpose of testing. This behavior only occurs when the application is published to the Azure App Service.

I've tried various different ContextOptions and variations of the connection string. I've read that a possible solution may be to use SSL with the PrincipalContext when establishing the connection to AD but when I try to implement this I'm getting a different error:

The server could not be contacted: System.DirectoryServices.Protocols.LdapException: The LDAP server is unavailable.

To get this to work I've tried appending the port number of LDAPS to the end of the connection string:

adContext = new PrincipalContext(ContextType.Domain, "10.0.0.1:636", c.Username, c.Password);

And also adding the context option for SSL to the command.

I'm able to telnet and test-netconnection to the server over port 636 but when executed either from the compiler or the app service I get the same error.

I was hoping someone would be able to find and issue with the way I'm connecting to Active Directory that could solve this issue or if the answer is to connect via SSL then provide some help in getting my connection to the server via SSL to work.

Many thanks

Upvotes: 1

Views: 377

Answers (1)

apan23
apan23

Reputation: 11

I managed it solve this after some further searching and trial and error. It turns out the reason for the Access Denied exception was that the connection wasn't using SSL as soon as I managed to configure SSL it started to work!

The issue with SSL is that I was using the IP address of the Domain Controller rather than the FQDN. It seems that the string used to connect to LDAPS must match the name on the certificate. I then added the Context Options: Negotiate, SSL and ServerBind and the connection was successful.

Upvotes: 0

Related Questions