我怎样才能检索到所有的角色(组)的用户是其成员?
-
11-09-2019 - |
题
有没有办法让角色在Windows身份验证的用户是在一个列表中,而不会被WindowsPrincipal.IsInRole
方法明确检查?
解决方案
WindowsPrincipal.IsInRole
只检查用户是否具有该名称的组的成员; Windows组是作用。你可以得到一个用户从WindowsIdentity.Groups
财产的成员组的列表。
您可以从您的WindowsIdentity
得到WindowsPrincipal
:
WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;
,也可以从上的WindowsIdentity工厂方法得到它:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsIdenity.Groups
是IdentityReference
的集合,其只是给你的组的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
。
不隶属于 StackOverflow