Search code examples
asp.netasp.net-coreauthorization.net-coreclaims-based-identity

Authorization Policy With Multiple Claims


I have created multiple authorization policies, each with 1 claim in it, doing a role check, like so:

options.AddPolicy("SuperAdminPolicy", policy => policy.RequireClaim(ClaimTypes.Role, "SuperAdmin"));

That all works fine.

However, I'm now at the point where I want to check 2 different types of claims, e.g. I want to make sure that the user has a specific role claim (As above), but I also want to check the value of a completely different claim (Such as first name). To clarify, I want to say something like " user must be in role 'x' and must have a first name claim value of 'bob'".

I can't quite figure out how to achieve this (And I'm sure it's probably quite straight forward).

Can someone point me in the right direction please?

Thanks.


Solution

  • We can actually chain the RequireClaim like this.

    services.AddAuthorization(option => {
    
                option.AddPolicy("SuperAdmin policy",
                policy =>  policy.RequireClaim(ClaimType.Role,"SuperAdmin")
                                  .RequireClaim(ClaimType.Name,"Bob"));
                                 });