代码之家  ›  专栏  ›  技术社区  ›  muratgu

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

  •  22
  • muratgu  · 技术社区  · 15 年前

    WindowsPrincipal.IsInRole 方法

    4 回复  |  直到 7 年前
        1
  •  48
  •   joshperry    8 年前

    WindowsPrincipal.IsInRole 只需检查用户是否是具有该名称的组的成员;Windows组 是一个 WindowsIdentity.Groups

    你可以 WindowsIdentity 从你的 WindowsPrincipal :

    WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;
    

    也可以从WindowsIdentity上的工厂方法获取:

    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    

    WindowsIdenity.Groups 是一组 IdentityReference 标识引用 变成 NTAccount 并获取值:

    var groupNames = from id in identity.Groups
                     select id.Translate(typeof(NTAccount)).Value;
    
        2
  •  9
  •   Steve Willcock    15 年前

    编辑:乔希赢了我!:)

    试试这个

    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
  •  7
  •   Seymour    6 年前

    如果未连接到域服务器,则 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
  •  1
  •   DigitalDan    7 年前

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

    将此添加到Web.config:

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

    Roles.GetRolesForUser() 获取用户所属的所有Windows组。确保你是正确的 using System.Web.Security .