我正在使用最新的.NET8和Blazor应用程序作为服务器端渲染.我正在try 将角色验证添加到应用程序中.我已经让我的Azure Web应用程序以及应用程序注册和身份验证工作了.我添加了角色,并将它们分配给了entra id中的用户.当我单步执行我的代码时,我可以看到roles声明,其中添加了我的自定义角色.当我试着使用<AuthorizeView Roles="Spec.Read"><p>you have spec.read role</p>时,它从来没有显示出来.以下是我到目前为止得到的信息:

myComponent.razor

<AuthorizeView>
    <p>Hello, @context.User.Identity?.Name</p> @*shows my e-mail as expected*@
    <p>Roles: @roles</p> @*shows the roles that is populated in the code section as expected. this includes "Spec.Read" *@
    <AuthorizeView Roles="Spec.Read" Context="childContext">
        <p>you are a spec reader</p> @* this never shows up *@
    </AuthorizeView>
</AuthorizeView>
...
@code{
    [CascadingParameter]
    Task<AuthenticationState> authenticationState{ get; set; }
    
    string roles = "";

    protected override async Task OnInitializedAsync()
    {
        SpecList = await CosmosDataSource.GetSpecList();

        if(authenticationState is not null)
        {
            var userIdentity = (ClaimsIdentity)(await authenticationState).User?.Identity;
            var claims = userIdentity.Claims;
            roles = claims.Where(x => x.Type == "roles").Select(x => x.Value).Aggregate((prev, next) => $"{prev}; {next}");
        }

        await base.OnInitializedAsync();
    }
}

以下是我用来添加ME ID(Microsoft Entra ID)的Program.cs代码片段,这似乎起作用了. program.cs

...
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).
    AddMicrosoftIdentityWebApp(builder.Configuration)
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

// Add services to the container.
builder.Services.AddRazorPages().AddMvcOptions(options=>
{
    var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
...

那么,我如何使用我的blazor组件的<AuthorizationView Roles=...部分中使用的角色声明呢?

另外,我可能做的Auth是完全错误的.这是我第一次实现auth,我正在try 遵循MS文档,但整个文档、框架和Net版本都有一点不一致.

picture showing the roles working in the blazor

picture of the roles working

debugger showing the roles claim

Debugger showing the roles claim

编辑:

我已经更新了我的程序cs add authentication,使其成为下面的代码片段:

builder.Services.AddAuthentication("MicrosoftOidc")
    .AddOpenIdConnect("MicrosoftOidc", oidcOptions =>
    {
        oidcOptions.Scope.Add(OpenIdConnectScope.OfflineAccess);
        oidcOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        oidcOptions.Authority = builder.Configuration["AzureAd:Instance"];
        oidcOptions.ClientId = builder.Configuration["AzureAd:ClientId"];
        oidcOptions.ClientSecret = builder.Configuration["AzureAd:ClientSecret"];
        oidcOptions.ResponseType = OpenIdConnectResponseType.Code;
        oidcOptions.MapInboundClaims = false;
        oidcOptions.TokenValidationParameters.NameClaimType = JwtRegisteredClaimNames.Name;
        oidcOptions.TokenValidationParameters.RoleClaimType = "role";
        oidcOptions.TokenValidationParameters.IssuerValidator = AadIssuerValidator.GetAadIssuerValidator(
            oidcOptions.Authority,
            oidcOptions.Backchannel).Validate;
    })
    .AddMicrosoftIdentityWebApp(builder.Configuration)
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

然而,我还是得到了同样的结果.我也try 过将RoleClaimType更改为"Roles",但没有更改.JsonWebTokenHandler.DefaultInboundClaimTypeMap同时定义了角色和角色,但两者都指向相同的角色架构

推荐答案

您定义了RoleClaimType了吗?因为缺省值是ClaimTypes.Role(http://schemas.microsoft.com/ws/2008/06/identity/claims/role),但您使用的是roles.

oidcOptions.MapInboundClaims = false;
oidcOptions.TokenValidationParameters.NameClaimType = JwtRegisteredClaimNames.Name;
oidcOptions.TokenValidationParameters.RoleClaimType = "roles";

请参阅:https://learn.microsoft.com/en-us/aspnet/core/blazor/security/server/blazor-web-app-with-oidc?view=aspnetcore-8.0&pivots=without-bff-pattern

Csharp相关问答推荐

.NET最小API映射将T参数列表为[FromQuery]

为什么我不能更改尚未设置的模拟对象属性的值?

如何在NServicebus中配置学习传输的文件夹(NService bus 8)

安装附加的. exe与Visual Studio

在C#中,DirectoryEntry返回空AuditRules集合,即使审计规则确实存在

有没有办法使.NET 6应用程序在特定的.NET 6运行时版本上运行

应用程序重新启动后,EFCore列表的BSON反序列化错误

如何使用C#中的主构造函数功能使用多个构造函数?

未找到任何HTTP触发器.成功部署Azure Functions Project后(c#)

如何捕获对ASP.NET核心应用程序的所有请求并将其发送到一个页面

每个http请求需要60秒,为什么?

BlockingCollection T引发意外InvalidOperationException

如何在VS代码中为C#DotNet配置.json选项以调试内部终端的控制台应用程序

未在数据流块之间传播完成

有空容错运算符的对立面吗?

VS 2022与VS 2019:如何/为什么创建额外的任务?

正在try 将自定义字体添加到我的控制台应用程序

Xamarin Forms应用程序中登录页面的用户名和密码编辑文本之间不需要的空格

Xamarin中出错.表单:应用程序的分部声明不能指定不同的基类

MudRadioGroup不切换