Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 551
Steviebob Avatar asked Mar 18 '17 13:03

Steviebob


2 Answers

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"));
                             });
like image 98
cpr43 Avatar answered Oct 17 '22 10:10

cpr43


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.

like image 28
Jason Coe Avatar answered Oct 17 '22 11:10

Jason Coe