如何检索用户所属的所有角色(组)?
WindowsPrincipal.IsInRole
只是检查用户是否是具有该名称的组的成员;一个Windows Group 是一个角色。您可以从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);
}
}
}
}
如果没有连接到域服务器,的翻译功能可能会抛出异常“//The trust relationship between this workstation and the primary domain failed.
” 但是对于大多数群体,这将是好了,personnally我使用:
foreach(var s in WindowsIdentity.GetCurrent().Groups) {
try {
IdentityReference grp = s.Translate(typeof (NTAccount));
groups.Add(grp.Value);
}
catch(Exception) { }
}
这就是答案。 – 2014-12-24 18:20:01
在一个ASP.NET MVC的网站,你可以做这样的:
添加到您的Web.config:
<system.web>
...
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
...
</system.web>
然后你可以使用Roles.GetRolesForUser()
让所有的Windows组用户是的成员。确保你是using System.Web.Security
。
我用`var identity = User.Identity作为WindowsIdentity;` – Jaider 2014-01-20 15:40:48