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());