【问题标题】:How can I retrieve all the roles (groups) a user is a member of?如何检索用户所属的所有角色(组)?
【发布时间】:2010-10-20 05:17:37
【问题描述】:

有没有办法在不通过WindowsPrincipal.IsInRole 方法显式检查的情况下获取 Windows 身份验证用户所在的角色列表?

【问题讨论】:

    标签: .net windows-identity rbac windows-principal


    【解决方案1】:

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

    您可以从您的WindowsPrincipal 获得WindowsIdentity

    WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;
    

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

    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    

    WindowsIdenity.GroupsIdentityReference 的集合,它只为您提供组的 SID。如果您需要组名,您需要将IdentityReference 转换为NTAccount 并获取值:

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

    【讨论】:

    • 我用var identity = User.Identity as WindowsIdentity;
    • 这个方法不显示我创建的新组,为什么?
    • 您必须注销并重新登录。此方法仅读取安全令牌。它不会再次查询 DC
    【解决方案2】:

    编辑:乔什打败了我! :)

    试试这个

    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】:

      如果没有连接到域服务器,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) {  }
      }
      

      【讨论】:

        【解决方案4】:

        在 ASP.NET MVC 站点中,您可以这样做:

        将此添加到您的 Web.config:

        <system.web>
          ...
          <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
          ...
        </system.web>
        

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

        【讨论】:

          猜你喜欢
          • 2019-07-07
          • 2018-09-30
          • 1970-01-01
          • 2023-03-10
          • 2023-03-21
          • 1970-01-01
          • 2012-05-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多