views:

315

answers:

2

Is there a way to get a list of roles a Windows authenticated user is in, without explicitly checking by WindowsPrincipal.IsInRole method?

+1  A: 

WindowsPrincipal.IsInRole just checks if the user is is a group with that name; Windows Group == Role. You can get a list of the groups that a user is in from the WindowsIdentity.Groups property.

You can get WindowsIdentity from your WindowsPrincipal:

WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;

or you can get it from a factory method on WindowsIdentity:

WindowsIdentity identity = WindowsIdenity.GetCurrent();

WindowsIdenity.Groups is a collection of IdentityReference which just gives you the SID of the group. If you need the group names you will need to translate the IdentityReference into an NTAccount and get the Value:

var groupNames = from id in idenity.Groups
                 select id.Translate(typeof(NTAccount)).Value;
joshperry
A: 

EDIT: Josh beat me to it! :)

Try this

using System;
using System.Security.Principal;

namespace ConsoleApplication5
{
    internal class Program
    {
     private static void Main(string[] args)
     {
      var identity = WindowsIdentity.GetCurrent();

      foreach (var groupId in identity.Groups)
      {
       var group = groupId.Translate(typeof (NTAccount));
       Console.WriteLine(group);
      }
     }
    }
}
Steve Willcock