[英]How can I retrieve all the roles (groups) a user is a member of?
有没有办法获取Windows身份验证用户所在的角色列表,而无需通过WindowsPrincipal.IsInRole
方法进行显式检查?
WindowsPrincipal.IsInRole
just checks if the user is a member of the group with that name; WindowsPrincipal.IsInRole
只检查用户是否是具有该名称的组的成员; a Windows Group is a Role. Windows组是一个角色。 You can get a list of the groups that a user is a member of from the WindowsIdentity.Groups
property. 您可以从WindowsIdentity.Groups
属性中获取用户所属组的列表。
You can get WindowsIdentity
from your WindowsPrincipal
: 您可以从WindowsPrincipal
获取WindowsIdentity
:
WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;
or you can get it from a factory method on WindowsIdentity: 或者您可以从WindowsIdentity上的工厂方法获取它:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsIdenity.Groups
is a collection of IdentityReference
which just gives you the SID of the group. WindowsIdenity.Groups
是IdentityReference
的集合, IdentityReference
为您提供组的SID。 If you need the group names you will need to translate the IdentityReference
into an NTAccount
and get the Value: 如果您需要组名,则需要将IdentityReference
转换为NTAccount
并获取值:
var groupNames = from id in identity.Groups
select id.Translate(typeof(NTAccount)).Value;
EDIT: Josh beat me to it! 编辑:乔希打败了我! :) :)
Try this 尝试这个
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);
}
}
}
}
If you are not connected to the domain server, the Translate
function may throw the following exception The trust relationship between this workstation and the primary domain failed.
如果未连接到域服务器,则Translate
功能可能会引发以下异常The trust relationship between this workstation and the primary domain failed.
But for most of the groups, it will be OK, so I use: 但是对于大多数人来说,它会没问题,所以我使用:
foreach(var s in WindowsIdentity.GetCurrent().Groups) {
try {
IdentityReference grp = s.Translate(typeof (NTAccount));
groups.Add(grp.Value);
}
catch(Exception) { }
}
In an ASP.NET MVC site, you can do it like this: 在ASP.NET MVC站点中,您可以这样做:
Add this to your Web.config: 将其添加到您的Web.config:
<system.web>
...
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
...
</system.web>
Then you can use Roles.GetRolesForUser()
to get all the Windows groups that the user is a member of. 然后,您可以使用Roles.GetRolesForUser()
来获取该用户所属的所有Windows组。 Make sure you're using System.Web.Security
. 确保您using System.Web.Security
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.