Active Directory COM Exception – An operations error occurred (0x80072020)

The issue is often that the context for which the Active Directory calls is made is under a user that does not have permissions (also can happen when identity impersonate="true" in ASP.NET, due to the fact that the users token is a “secondary token” that cannot be used when authenticating against another server from: https://social.technet.microsoft.com/Forums/en-US/f188029c-51cf-4b50-966a-eee7160d0353/an-operations-error-occured).

The following code will ensure that the block of code your are running, is run under the context of say the AppPool (i.e. NETWORKSERVICE) that your service or site is running under.

using (HostingEnvironment.Impersonate())
{
   var domainContext = new PrincipalContext(ContextType.Domain, "myDomain.com");
   var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.Name, "PowerUsers");
   if (groupPrincipal != null)
   {
      //code to get the infomation
   }

}

However, one super important detail is that all the code calling Active Directory must be in that block. I had used some code a team member of mine wrote that was returning a LINQ query results of type Users (custom class), but not evaluting the expression (bad practice). Therefore the expression tree was returned instead of the results.

What ended up happening is the calling code eventually evaluated the results and the An operations error occurred message still appeared. I though the code fix above didn’t work. When in fact it did, but there was code evaluating the results outside the block.

In a nutshell, make sure all code to access Active Directory is inside that using block and the exception should be fixed one the service/app is deployed to the server.

Leave a Comment