Sunday, September 20, 2015

Getting a UserPrincipal object

I was trying relentlessly to find a way to get a UserPrincipal out of a WindowsIdentity object - because this was the only identity object I had in my application, and I was sure that whatever other identity data I would need should come from it.

Well, first of all I found out that you can create a WindowsPrincipal out of a WindowsIdentity object, just using one of WindowsPrincipal's constructors.

But most importantly, I did succeed in obtaining a UserPrincipal - but with no relation whatsoever to my Identity object.

Let me just single out the most common reason why you would be interested in a UserPrincipal object - to get a user name, out of its user string.

So, back to getting a UserPrincipal, the only pre-requisite is to have the related Domain (the Active Directory domain the user is related to) at hand. Once you have it, then all you need is:


PrincipalContext ctx = new PrincipalContext(ContextType.Domain, _domain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Usf);

No comments:

Post a Comment