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.
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 ([email protected]) - 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.
I dealt with this same problem. See discussion on similar question. https://stackoverflow.com/a/8347817/2012977
Solution is below:
public List<GroupPrincipal> GetGroups(string userName)
{
var result = new List<GroupPrincipal>();
PrincipalContext ctx = GetContext(); /*function to get domain context*/
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName);
if (user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
var iterGroup = groups.GetEnumerator();
using (iterGroup)
{
while (iterGroup.MoveNext())
{
try
{
Principal p = iterGroup.Current;
result.Add((GroupPrincipal) p);
}
catch (PrincipalOperationException)
{
continue;
}
}
}
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With