简体   繁体   中英

Blazor WASM .NET-6 Role Authentication is not working for me

My project is in VS-2022 and using the TAGS below.

Can someone please explain what the code-snippet reference below means in the SERVER program.cs file? What is this snippet intended to "do"?
Specifically, what does the "name" and "role" refer to? I have already created four roles in the AspNetRoles-table and also AspNetRoleClaims and AspNetUserClaims. However, the following Blazor-page condition does NOT work: @attribute [Authorize(Roles = "Owner,Admin,Lead,User")]

I found the following code-segment in a suggestion that I need this code to get the role authorization work.

When used, I get a runtime error "Sequence contains no elements" on the line containing: options.ApiResources.Single().UserClaims.Add("name");

I am out of my element in knowing what is needed in the program.cs file sections, formerly called startup.cs, due to reading .NET Core 3.1 and .NET 5 online tutorials to get my project into .NET 6 and WASM hosted.Much has changed from the past two years especially with Blazor and .NET 6.

I welcome questions, comments and solutions to getting role authorization working in my project.

builder.Services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
           options.IdentityResources["openid"].UserClaims.Add("name");
           options.ApiResources.Single().UserClaims.Add("name");
           options.IdentityResources["openid"].UserClaims.Add("role");
           options.ApiResources.Single().UserClaims.Add("role");
        });

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");

There are too many too smart variations out there.

Try this official doc.

Name and role claim with API authorization

The Profile Service one.

Create ProfileService.cs under server project.

using IdentityModel;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using System.Threading.Tasks;

public class ProfileService : IProfileService
{
    public ProfileService()
    {
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var nameClaim = context.Subject.FindAll(JwtClaimTypes.Name);
        context.IssuedClaims.AddRange(nameClaim);

        var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
        context.IssuedClaims.AddRange(roleClaims);

        await Task.CompletedTask;
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        await Task.CompletedTask;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM