Finding Out which Groups a User is a Member Of When Using Windows Authentication in Asp.Net

When using Windows authentication with, 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<string> GetGroups(RolePrincipal user)
    List<string> groups = new List<string>();

    WindowsIdentity identity = p.Identity as WindowsIdentity;
    foreach (IdentityReference group in identity.Groups)
        NTAccount account = (NTAccount)group.Translate(typeof(NTAccount));


    return groups;

the user of it on a web page would be something like:

List<string> 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.

kick it on

3 Responses to Finding Out which Groups a User is a Member Of When Using Windows Authentication in Asp.Net

  1. Gyan Ranjan says:


    Great Article.. helped alot
    but what is p inp.Identity as WindowsIdentity;

    if you explain a bit more it will be more helpful to freshers/beginners/ or persone new to this concept


  2. lust says:

    great tip, one more question – how to use that code when i need to know membership of other user (not the current user)

  3. Outstanding post however , I was wanting to know ifnyou could write a litte more on this subject?nI’d be very grateful if you could elaborate a little bit more. Kudos! Come on

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: