When a user is Windows authenticated in my WebAPI app, and I use UserPrincipal.Current
, I get the error that
System.DirectoryServices.AccountManagement.GroupPrincipal cannot be converted to System.DirectoryServices.AccountManagement.UserPrincipal
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue) at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()
I am not the only one to have this problem.
But I have the ApiController.User
object filled correctly. So I tried:
Principal principal = (Principal)User;
principal.GetUnderlyingObject(...
But it won't do, because
IPrincipal cannot be converted to Principal
So, I have to convert to a Windows principal, which works:
WindowsPrincipal winPrincipal = (WindowsPrincipal)User;
And then I have to ask AD for that specific user:
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
Principal principal = Principal.FindByIdentity(pc, windowsPrincipal.Identity.Name);
principal.GetUnderlyingObject(...
}
In 9 of 10 cases this works, but for some users, principal is null, although the user is authenticated. The affected users are all part of a certain subdomain. What am I overlooking? Is there another, more reliable, method to always get the AD principal of the Windows authenticated principal?