15

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.

Steviebob
  • 1,705
  • 2
  • 23
  • 36

3 Answers3

26

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"));
                             });
cpr43
  • 2,942
  • 1
  • 18
  • 18
1

I did a little additional research on this post as I was looking for something very similar. I noticed there is a policy.RequireRole and policy.RequireUser in addition to RequireClaim. Thus, a policy can require a claim, role, user, or any combination.

Jason Coe
  • 11
  • 1
1

Also you can add multiple arguments to the RequireClaim statement for Example If you want to accept multiple Roles:

options.AddPolicy("AdminPolicy", policy => policy.RequireClaim(ClaimTypes.Role, "SuperAdmin" , "Admin"));
alirezacode
  • 116
  • 4