代码之家  ›  专栏  ›  技术社区  ›  Muflix

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

  •  0
  • Muflix  · 技术社区  · 7 年前

    在里面 我在我的服务中使用了这个代码

    HttpContext.Current.Request.LogonUserIdentity.Groups
                        .Any(x => x.Translate(typeof(NTAccount)).Value == "some role"
    

    而且效果很好。 .net核心mvc 2.1.2 我通过了 IHttpContextAccessor

    _httpAccessor.HttpContext.User.Identity.LogonUserIdentity.Groups
    

    Identity 不包含 LogonUserIdentity . 我试图找到任何解决方案,但我没有成功,我如何才能得到用户组列表或检查用户是否是特定的一个成员?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Nan Yu    7 年前

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

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