Sabarish Sathasivan
Sabarish Sathasivan

Reputation: 1276

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

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

Upvotes: 0

Views: 826

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11896

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

Upvotes: 0

Related Questions