1

I have a React project with API (net core). My website menus/fields will be shown/hidden based on the Role of the user. The user will login to my website via external oidc.

However, the access_token and id_token coming from the oidc doesn't have the Role information, it will only have their email, which I will use to check against my Database to determine which Role is the logged in user. Currently I have an API to get Role based on their access_token, so it's something like

public string getRoles(string access_token)
{
    //check Database
    return role;
}  

This function will be called in almost every page so I was wondering is there any more efficient way to do this?

tickwave
  • 3,335
  • 6
  • 41
  • 82
  • What I think the ideal solution about your scenario is adding the user role claim to the access token and we can use attribute liken `[Authorize(Roles = "Watever")]` to validate the role, so can [this answer](https://stackoverflow.com/a/51892911/14574199) help you? – Tiny Wang Sep 23 '21 at 01:39

1 Answers1

1

You need to add the claim to the HttpContext.User when the signin is confirmed with the role from the DB. When you define this connection in your startup, be sure to handle the OnTokenValidated event.

.AddOpenIdConnect("oidc", options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async ctx =>
        {
            var claim = new Claim("Role", "TheirRole");

            var identity = new ClaimsIdentity(new[] { claim });

            ctx.Principal.AddIdentity(identity);

            await Task.CompletedTask;
        }
    };
}

Then you can access this within the controller (or anywhere with HttpContext) like so

var claim = HttpContext.User.Claims.First(c => c.Role == "TheirRole");
Ben Matthews
  • 499
  • 2
  • 5
  • This is what I currently do, onTokenValidated is actually being called over and over. So I was wondering if there's a better solution. – tickwave Sep 22 '21 at 17:40