Finding Out which Groups a User is a Member Of When Using Windows Authentication in Asp.Net
When using Windows authentication with Asp.net, I often need to know which active directory groups a user is a member of. Now I know that you can do something like:
if (User.IsInRole("Admin"))
{
//Give Access to Secrets
}
The problem with this is you need to know the name of the group ahead of time. And what if you are on a network where the full name of a group is not always clear. The actual group name may be "MyDomain\Admin". So I wrote up a quick way to just get a list of all the groups a user is a member of. It isn't super straight forward (as far as which types you need to cast to) so I thought I would list it out here:
public static List GetGroups(RolePrincipal user)
{
List groups = new List();
WindowsIdentity identity = p.Identity as WindowsIdentity;
foreach (IdentityReference group in identity.Groups)
{
NTAccount account = (NTAccount)group.Translate(typeof(NTAccount));
groups.Add(account.Value);
}
return groups;
}
the user of it on a web page would be something like:
List groups = GetGroups(User as RolePrincipal);
Keep in mind that this is assuming you are using Windows Authentication. So the weird part of the code above is:
NTAccount account = (NTAccount)group.Translate(typeof(NTAccount));
if you do not get this step, you will just get a bunch of Active Directory IDs that won't do you much good.
Also, sorry about the long title. I just can't think of a clever title today. Maybe I should add something like "Ultimate Edition for Developers" on the end to make it extra clear.