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:

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));
		groups.Add(account.Value);
	}
	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 DotNetKicks.com

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .Net | C#
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

October 13. 2008 12:48