如何检索用户所属的所有角色(组)?

31

有没有一种方法可以获取 Windows 认证用户所在的角色列表,而不是通过 WindowsPrincipal.IsInRole 方法进行显式检查?

4个回答

51

WindowsPrincipal.IsInRole仅检查用户是否是该名称组的成员; Windows组角色。 您可以从WindowsIdentity.Groups属性中获取用户是成员的组列表。

您可以从您的WindowsPrincipal获取WindowsIdentity

WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;

或者你可以从WindowsIdentity上的一个工厂方法获取它:

WindowsIdentity identity = WindowsIdentity.GetCurrent();

WindowsIdentity.Groups 是一个 IdentityReference 集合,它只提供组的 SID。如果您需要组名称,则需要将 IdentityReference 转换为 NTAccount 并获取其值:

var groupNames = from id in identity.Groups
                 select id.Translate(typeof(NTAccount)).Value;

2
我使用了 var identity = User.Identity as WindowsIdentity; - Jaider
为什么这个方法不显示我创建的新组? - martis martis
你需要注销并重新登录。这种方法只读取安全令牌,不会再次查询DC。 - user1034912

9

编辑:Josh已经完成了! :)

试试这个

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

7
如果您未连接到域服务器,则 Translate 函数可能会抛出以下异常:The trust relationship between this workstation and the primary domain failed. 但对于大多数组而言,这将是可以的,因此我使用:
foreach(var s in WindowsIdentity.GetCurrent().Groups) {
    try {
        IdentityReference grp = s.Translate(typeof (NTAccount)); 
        groups.Add(grp.Value);
    }
    catch(Exception) {  }
}

1
在ASP.NET MVC网站中,您可以像这样做:
将以下内容添加到您的Web.config文件中:
<system.web>
  ...
  <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
  ...
</system.web>

然后,您可以使用Roles.GetRolesForUser()来获取用户所属的所有Windows组。请确保您正在using System.Web.Security

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接