I am having an issue using the GetAuthorizationGroups method of the UserPrincipal class in a web application.
Using the following code, I am receiving "While trying to retrieve the authorization groups, an error (5) occurred"
PrincipalContext context = new PrincipalContext(ContextType.Domain, null, "DC=MyCompany,DC=COM", "username", "password");
UserPrincipal p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "joe.blogs");
var groups = p.GetAuthorizationGroups();
I believe this code works to an extent.
- When I view the context object, I can see the server and username/password have been resolved correctly in the object
- When I view the p object, I can see AD details have been populated like phone no etc.
Here is the stack trace from the error.
[PrincipalOperationException: While trying to retrieve the authorization groups, an error (5) occurred.]
System.DirectoryServices.AccountManagement.AuthZSet..ctor(Byte[] userSid, NetCred credentials, ContextOptions contextOptions, String flatUserAuthority, StoreCtx userStoreCtx, Object userCtxBase) +317279
System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p) +441
System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper() +78
System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups() +11
By removing the username and password details from the PrincipalContext constructor and changing the applicationpool (in iis7) to run as the same user (username@mycompany.com) - the following code works.
PrincipalContext context = new PrincipalContext(ContextType.Domain, null, "DC=MyCompany,DC=COM");
UserPrincipal p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "joe.blogs");
var groups = p.GetAuthorizationGroups();
I need to get the code in the first example to work - I do not want run the application pool as a domain user just to get this code working.
Error 5 indicates ERROR_ACCESS_DENIED, which suggests a permissions related issue. That said, the following code has just worked for me, running on Windows 7 with the website running as the default application pool:
Content of "body" of .aspx page:
Code-behind:
In my example
logon_domain
was the lefthand ofdomain_name\username
, rather than the style of domain specification you'd used. My solution may or may not work for you. If it doesn't, it does point to a permissions issue somewhere.I dealt with this same problem. See discussion on similar question. https://stackoverflow.com/a/8347817/2012977
Solution is below:
Have your administrator look at the AD account for the user that returns the error code 5. I ran into that today and it turned out to be a setting on that user's account. There is a checkbox to inherit security settings that was not checked (all the other users were checked). This solved it for me.