如何检查用户是否是组成员

Muf*_*lix 3 asp.net-mvc asp.net-core

我的目标是检查用户是否是特定活动目录组的成员。

.net mvc中,我在我的服务中使用了这段代码

HttpContext.Current.Request.LogonUserIdentity.Groups
                    .Any(x => x.Translate(typeof(NTAccount)).Value == "some role"
Run Code Online (Sandbox Code Playgroud)

效果很好。在.net core mvc 2.1.2中,我传递IHttpContextAccessor到服务构造函数并尝试使用以下内容

_httpAccessor.HttpContext.User.Identity.LogonUserIdentity.Groups
Run Code Online (Sandbox Code Playgroud)

但有一个问题,因为Identity不包含LogonUserIdentity. 我尝试找到任何解决方案,但没有成功,如何获取用户组列表或检查用户是否是特定组的成员?

Nan*_* Yu 7

除了使用内置功能按“角色”检查权限外,如果您想按特定AD组检查权限,还可以使用以下代码:

 public static class Security
{
    public static bool IsInGroup(this ClaimsPrincipal User, string GroupName)
    {
        var groups = new List<string>();

        var wi = (WindowsIdentity)User.Identity;
        if (wi.Groups != null)
        {
            foreach (var group in wi.Groups)
            {
                try
                {
                    groups.Add(group.Translate(typeof(NTAccount)).ToString());
                }
                catch (Exception)
                {
                    // ignored
                }
            }
            return groups.Contains(GroupName);
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

并用作:

 if (User.IsInGroup("GroupName"))
 {

 }
Run Code Online (Sandbox Code Playgroud)

  • 谢谢, `_httpAccessor.HttpContext.User.IsInRole("&lt;Domain&gt;\\&lt;SpecificGroupName&gt;")` 也有效。 (5认同)