Skip to content

[Blazor][Wasm] Using roles with ApiAuthorization + Blazor #17649

@javiercn

Description

@javiercn

[EDIT by guardrex to add the topic metadata]

Feel free to dupe this issue with some other issue, I couldn't find a specific one.

Content is here:

Steps for using roles with ApiAuthorization + Client-side Blazor

  • Configure Identity to use roles by calling AddRoles
    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
  • Configure identity server to put the role claim into the id token and the access token and prevent the default mapping for roles in the JwtSecurityTokenHandler.
    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
            options.IdentityResources["openid"].UserClaims.Add("role");
            options.ApiResources.Single().UserClaims.Add("role");
        });
    
    // Need to do this as it maps "role" to ClaimTypes.Role and causes issues
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");
  • On your blazor application use [Authorize(Roles = "admin")] or any other role your app defines.
  • On your protected resource APIs use [Authorize(Roles = "admin")] or any other role your app defines.

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

Status

Done

Relationships

None yet

Development

No branches or pull requests

Issue actions