12
votes

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.

2

2 Answers

20
votes

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"));
                             });
1
votes

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.