有没有办法让角色在Windows身份验证的用户是在一个列表中,而不会被WindowsPrincipal.IsInRole方法明确检查?

有帮助吗?

解决方案

WindowsPrincipal.IsInRole只检查用户是否具有该名称的组的成员; Windows组作用。你可以得到一个用户从WindowsIdentity.Groups财产的成员组的列表。

您可以从您的WindowsIdentity得到WindowsPrincipal

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;

其他提示

编辑:乔希打我吧! :)

尝试此

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

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

在一个ASP.NET MVC的网站,你可以做这样的:

添加到您的Web.config:

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

然后你可以使用Roles.GetRolesForUser()让所有的Windows组用户是的成员。请确保你using System.Web.Security

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top