Retrieving roles from token in Razor page app

Hi,

I’ve been following the article at https://auth0.com/blog/securing-razor-pages-applications-with-auth0/, and looking at how user details are pulled out of the token (the example shows email being extracted by adding

options.Scope = “openid profile email”;

to AddAuth0WebAppAuthentication.)

I have added an action to add the roles to the token. How would I go about retrieving these roles, and how could I use them in the standard [Authorize] flow?

So, I can get the details of the Auth0 roles assigned by querying the Claims collection of the User object. I am still unclear how to convert this is into a Role that the User belongs to when queried with User.IsInRole(“rolename”), or so it is usable in policy-based authorization e.g. via a policy like

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("RequireAdministratorRole",
         policy => policy.RequireRole("Administrator"));
});

Looking at an example from the Github for auth0.aspnetcore.authentication, the roles have to be added into the token in a specific way to be recognised by asp.net. It gives details of a rule:

function (user, context, callback) {
  const assignedRoles = (context.authorization || {}).roles;
  const idTokenClaims = context.idToken || {};

  idTokenClaims['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'] = assignedRoles;

  context.idToken = idTokenClaims;

  callback(null, user, context);
}

Presumably this would have to be rewritten as an Action, any clues what this should look like, please?

For reference, I rewrote this as

exports.onExecutePostLogin = async (event, api) => {
  const assignedRoles = (event.authorization || {}).roles;
  
  if (event.authorization) {
    api.idToken.setCustomClaim('http://schemas.microsoft.com/ws/2008/06/identity/claims/role', assignedRoles);
    api.accessToken.setCustomClaim('http://schemas.microsoft.com/ws/2008/06/identity/claims/role', assignedRoles);
  }
}
``` and it works as required.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.