Is there a way to get a list of roles a Windows authenticated user is in, without explicitly checking by WindowsPrincipal.IsInRole method?
How can I retrieve all the roles (groups) a user is a member of?
28.7k Views Asked by muratgu At
4
There are 4 best solutions below
0
On
In an ASP.NET MVC site, you can do it like this:
Add this to your Web.config:
<system.web>
...
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
...
</system.web>
Then you can use Roles.GetRolesForUser() to get all the Windows groups that the user is a member of. Make sure you're using System.Web.Security.
0
On
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);
}
}
}
}
0
On
If you are not connected to the domain server, the Translate function may throw the following exception The trust relationship between this workstation and the primary domain failed.
But for most of the groups, it will be OK, so I use:
foreach(var s in WindowsIdentity.GetCurrent().Groups) {
try {
IdentityReference grp = s.Translate(typeof (NTAccount));
groups.Add(grp.Value);
}
catch(Exception) { }
}
WindowsPrincipal.IsInRolejust checks if the user is a member of the group with that name; a Windows Group is a Role. You can get a list of the groups that a user is a member of from theWindowsIdentity.Groupsproperty.You can get
WindowsIdentityfrom yourWindowsPrincipal:or you can get it from a factory method on WindowsIdentity:
WindowsIdenity.Groupsis a collection ofIdentityReferencewhich just gives you the SID of the group. If you need the group names you will need to translate theIdentityReferenceinto anNTAccountand get the Value: