最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - ASP.NET Core Web API : failure to validate role in token - Stack Overflow

programmeradmin5浏览0评论

My C# ASP.NET Core Web API is using token validation. The API has multiple clients using different roles.

I'm using policies with different roles to authorize requests to different endpoints.

For one of the clients I'm getting the error

Authorization failed. These requirements were not met: RolesAuthorizationRequirement:User.IsInRole must be true for one of the following roles: ("Content of EntraRoles.ReadAll"|"content of EntraRoles.ReadWriteAll"|"content of EntraRoles.ReadWriteUploadStatus")

The client that fails uses the role

EntraRoles.ReadWriteFileUploadAndCreateOperator

Based upon the fallback policy in the code below the error message above does not make any sense to me.

Why is the content of EntraRoles.ReadWriteFileUploadAndCreateOperator not present in the error message?

What am I doing wrong?

The request is validated in Azure API manager before forwarded to my API. The APIM policy validate-azure-ad-token validates the roles, issuer and audience.

The token must contain one of the 4 entra roles added in the code below. So if the token did not have the role EntraPolicy.ReadWriteFileUploadAndCreateOperator the request should have failed in APIM.

APIM says token is ok, and contains EntraPolicy.ReadWriteFileUploadAndCreateOperator.

My API says token is missing one of the 3 other roles, even though the code uses 4 roles.

My program.cs uses this code to set up authentication and authorization:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthorizationBuilder()
    .AddPolicy(EntraPolicy.ReadAll, policy => policy.RequireRole(EntraRoles.ReadAll,
                                                                EntraRoles.ReadWriteAll,
                                                                EntraRoles.ReadWriteUploadStatus))
    .AddPolicy(EntraPolicy.ReadWriteAll, policy => policy.RequireRole(EntraRoles.ReadWriteAll))
    .AddPolicy(EntraPolicy.ReadWriteAllOrReadWriteUploadStatus, policy => policy.RequireRole(EntraRoles.ReadWriteAll,
                                                                EntraRoles.ReadWriteUploadStatus))
    .AddPolicy(EntraPolicy.ReadWriteFileUploadAndCreateOperator, policy => policy.RequireRole(EntraRoles.ReadWriteAll,
                                                                EntraRoles.ReadWriteFileUploadAndCreateOperator))
    .SetFallbackPolicy(new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .RequireRole(EntraRoles.ReadAll, EntraRoles.ReadWriteAll, EntraRoles.ReadWriteUploadStatus, EntraRoles.ReadWriteFileUploadAndCreateOperator)
                        .Build());
发布评论

评论列表(0)

  1. 暂无评论