Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate user agains policy in code in aspnet core?

All tutorials I've seen show you how to protect action just by adding

[Authorize(Policy = "admin")]

to controller or action.

But, rather than throwing error, I need to return to browser (in json) the answer to the question if someone is an "admin" and none of sources tells how to do that. Yes you can check claim (User.HasClaim), but policies are made of multiple claims.

So how do I do that?

like image 740
doker Avatar asked Apr 05 '17 12:04

doker


People also ask

What is policy based authorization in .NET Core?

In ASP.NET Core, the policy-based authorization framework is designed to decouple authorization and application logic. Simply put, a policy is an entity devised as a collection of requirements, which themselves are conditions that the current user must meet.

What is Modelstate in ASP.NET Core?

Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field.

What is AddAuthorizationCore?

AddAuthorizationCore(IServiceCollection)Adds authorization services to the specified IServiceCollection. C# Copy. public static Microsoft.Extensions.DependencyInjection.


1 Answers

In the constructor of your controller you can take a dependency on IAuthorizationService authorizationService to have it injected. Then you can use that to check if the user meets the policy like this:

var isAuthorized = await authorizationService.AuthorizeAsync(User, "admin");

where "admin" is the name of the policy

like image 167
Joe Audette Avatar answered Oct 21 '22 00:10

Joe Audette