Spontaneous Publicity
blogs are the new phone book

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

March 13, 2008 08:44 by Luke

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:

[code=csharp] if (User.IsInRole("Admin")) { //Give Access to Secrets } [/code] 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: [code=csharp] 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; } [/code] the user of it on a web page would be something like: [code=csharp] List groups = GetGroups(User as RolePrincipal); [/code]

Keep in mind that this is assuming you are using Windows Authentication. So the weird part of the code above is:

[code=csharp] NTAccount account = (NTAccount)group.Translate(typeof(NTAccount)); [/code]

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 DotNetKicks.com
Tags:
Categories:
Actions: E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed