Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5 Authorize against two or more policies (OR-combined policy)

Is it possible to apply authorization against two or more policies? I am using ASP.NET 5, rc1.

[Authorize(Policy = "Limited,Full")] public class FooBarController : Controller {     // This code doesn't work } 

If not, how may I achieve this without using policies? There are two groups of users that may access this controller: "Full" and "Limited". Users may either belong to "Full" or "Limited", or both. They only require to belong to one of the two groups in order to access this controller.

like image 877
painiyff Avatar asked Feb 24 '16 18:02

painiyff


People also ask

How would you apply an authorization policy to a controller in an ASP NET core application?

Role-Based Authorization in ASP.NET Core You can specify what roles are authorized to access a specific resource by using the [Authorize] attribute. You can even declare them in such a way that the authorization evaluates at the controller level, action level, or even at a global level. Let's take Slack as an example.

Under Which method should a policy be registered for it to be a part of the authorization service?

Authorization Policy The user must satisfy all the requirements. We Add the policy using the AddAuthorization method in the ConfigureServices of the startup class.

What is IHttpContextAccessor?

IHttpContextAccessor Interface (Microsoft.AspNetCore.Http)Provides access to the current HttpContext, if one is available.

What is IAuthorizationRequirement?

The IAuthorizationRequirement will contain pure data (reads: No services, no dependencies that need to be injected) required for your requirement, the handler will validate it.


2 Answers

Not the way you want; policies are designed to be cumulative. For example if you use two separate attributes then they must both pass.

You have to evaluate OR conditions within a single policy. But you don't have to code it as ORs within a single handler. You can have a requirement which has more than one handler. If either of the handlers flag success then the requirement is fulfilled. See Step 6 in my Authorization Workshop.

like image 117
blowdart Avatar answered Oct 10 '22 10:10

blowdart


Once setting up a new policy "LimitedOrFull" (assuming they match the claim type names) create a requirement like this:

options.AddPolicy("LimitedOrFull", policy =>     policy.RequireAssertion(context =>         context.User.HasClaim(c =>             (c.Type == "Limited" ||              c.Type == "Full")))); 

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1#using-a-func-to-fulfill-a-policy

like image 30
Andrius Naruševičius Avatar answered Oct 10 '22 10:10

Andrius Naruševičius