0

I'm having some difficulties with AD authentication, I log the user in using the angular MSAL library and send the bearer token to the backend.

Backend handles it perfectly and stores the userclaim. What happens though is that the groups the user is part of in AD are not in this claim. This is because there are too many groups in AD and Azure just returns "hasgroups : true". This is fine and I just retrieve the user groups using the Graph API.

Only now I'm wondering, how do I add the retrieved groups to the existing user claim? My end goal is that I can authorize certain groups to controllers using the following code:

[Authorize(Roles = "EmployeeOnly")]
Rick
  • 109
  • 13

1 Answers1

0

To add a Claim to a ClaimsIdentity you can use the ClaimsIdentity.AddClaim(Claim) Method using the ClaimType 'Role'

The code could look something like this:

var claimsIdentity = context.Authentication.User.Identity as ClaimsIdentity;

if (claimsIdentity == null || !claimsIdentity.IsAuthenticated) 
{
    return;
}

claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "YourRoleHere"));

EDIT:
Of course this is only a one-off action since you're not updating the identity on the front-end. So the next call will not have the updated identity. And I would expect you don't want to call the Graph API for every request that comes in. Right?

A few options I can think of:

  • Think about caching the user roles somewhere and getting them from there for each request during that session. For instance by using an ActionFilter.
  • Depending on the type of frontend you're using, see if you can update the token there.

To be able to help you better, investigate this some more, try some things and open a new question if you can't get it to work.

rickvdbosch
  • 14,105
  • 2
  • 40
  • 53
  • Thanks! That works perfectly. However when I make a new call to my API the claims I just added are gone. Most likely because the API overwrites the claim with the new bearer token that is sent from the frontend. What would be the best approach to solve this you think? Do I need to execute this controller method every time before any other controller method is executed? Or should I make a base class or something? – Rick Jun 17 '19 at 11:56
  • Please update your question with the additional information. I've updated my answer to give some more context. – rickvdbosch Jun 17 '19 at 12:19
  • This may be a use-case for the IClaimsTransformation interface. I describe it in an answer to my own question here: https://stackoverflow.com/a/57999880/3241128 – bubbleking Oct 02 '19 at 20:49