How can I retrieve all the roles (groups) a user is a member of?

柔情痞子 提交于 2019-11-29 16:12:32

问题


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


回答1:


WindowsPrincipal.IsInRole just 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 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 = WindowsIdentity.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 identity.Groups
                 select id.Translate(typeof(NTAccount)).Value;



回答2:


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);
            }
        }
    }
}



回答3:


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) {  }
}



回答4:


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.



来源:https://stackoverflow.com/questions/762245/how-can-i-retrieve-all-the-roles-groups-a-user-is-a-member-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!