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?
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.
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.
AddAuthorizationCore(IServiceCollection)Adds authorization services to the specified IServiceCollection. C# Copy. public static Microsoft.Extensions.DependencyInjection.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With