Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if user is member of group

My goal is to check if user is member of specific active directory group.

In .net mvc i was using this code inside my service

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

and it worked well. In .net core mvc 2.1.2 i pass IHttpContextAccessor into service constructor and try to use following

_httpAccessor.HttpContext.User.Identity.LogonUserIdentity.Groups

but there is an issue, because Identity does not contains LogonUserIdentity. I tried to find any solution but i was not successful, how can i get the list of user groups or check if user is member of specific one ?

like image 995
Muflix Avatar asked Dec 11 '25 07:12

Muflix


1 Answers

Except using built-in function which check the permission by "Roles", if you want to check by specific AD Group, you can also use below codes :

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

And using as:

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

 }
like image 139
Nan Yu Avatar answered Dec 14 '25 07:12

Nan Yu