Validate a claim with multiple values in ASP.NET Core Web API

523 views Asked by At

We are using Okta as our IDP and performing authorization using bearer token. Our scp claim has the following values

"scp": [
    "claim1",
    "claim2",
    "claim3",
    "claim4",
    "claim5"
    ]

We are using the following code in our asp.net web api to define a policy for authorization

services.AddAuthorization(
    options =>
    {
        options.AddPolicy(
            "HasClaim1", builder =>
            builder.RequireClaim("scp", "claim1"));
    });

We are using the following code to add authorization to our controllers

[Authorize(Policy = "HasClaim1")]
public class TestController : ControllerBase
{
 }

The validation fails with the following error message

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Authorization failed. These requirements were not met:
ClaimsAuthorizationRequirement:Claim.Type=scp and Claim.Value is one of the following values: (claim1)

Any help is appreciated

1

There are 1 answers

1
Ruikai Feng On

You could try with the codes below ,insert a break point and check the claims ontokenvalidated when you debug:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(op =>
{
    op.Events = new JwtBearerEvents()
    {
        OnTokenValidated = context =>
        {
            var claims = context.Principal.Claims;
            return Task.CompletedTask;
        }
    };
    .....
});

enter image description here

So it should be :

builder.Services.AddAuthorization(x => x.AddPolicy("HasClaim1", builder=>builder.RequireClaim("http://schemas.microsoft.com/identity/claims/scope", "Claim1")));

For your requirement