Search code examples
active-directoryasp.net-core-mvcrolesactive-directory-groupasp.net-authorization

Asp net core MVC Authorization with Active Directory


In an Asp net core MVC application, I use Active Directory for automatic login like this :

this.user = UserPrincipal.FindByIdentity(this.context, Environment.UserName);

and I get groups of the user with this :

public List<String> GetUserGroups()
{
   List<String> groups = new List<String>();
   foreach(GroupPrincipal gr in user.GetGroups())
   {
      groups.Add(gr.Name);
   }
   return groups;
}

And I would like to implement Autorisation with this groups, something like that :

[Authorize(Roles ="Admin")]
public IActionResult OnlyAdmin(){}

with something that link AD groups with authorization Roles or directly check authorization with AD groups if possible but I don't know how to do something like that.

note : I haven't any login/logout pages, it's only automatic.

EDIT

Don't know exactly why or how but it finaly work whithout any code and only with the user login in the PC not the user specified in this.user but it's fine like that.

But now I get a 404 error when I'm trying to access a denied page, why it's not a 401 or 403 error ? How can I redirect a denied access to a custom error page ?


Solution

  • You need to add the group in the ClaimsPrincipal class, i.e.

    var claims = new List<Claim>();
    claims.Add(new Claim(ClaimTypes.Name, username));
    foreach (string userGroup in authResponse)
    {
        claims.Add(new Claim(ClaimTypes.Role, userGroup, ClaimValueTypes.String,"system","system"));
    }
    
    var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "authenticationScheme"));
    

    Now use authorize attribute, either on controller or action as :

    [Authorize(Roles = "guest,home")]