Search code examples
asp.net-coreasp.net-core-mvc

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?


Solution

  • 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