The goal of this post is to show how can we protect controller actions in ASP.NET Core 1 using Policies.
The whole code is available on GitHub: ASP.NET Core 1, Security using Policies.
With policies we don’t need to hard code anymore Roles or Names in our Authorize attribute. A policy is an authorization logic that contains one of more requirements.
How to use a policy?
The concept is very simple, once we have a defined policy we can add it to our Authorize attributes…
How to create a policy?
We have to define our policies in our Startup class, in ConfigureServices. We need a policy name, a list of valid authentication schemes and a list of requirements.
We can add more than one requirement to our policy, there are some pre-build requirements:
But the more flexible way is to add a custom requirement, doing this we can write our own logic:
- policy.AddRequirements(new IsGoodMonsterRequirement());
To write our requirement we use the base class AuthorizationHandler and implement the interface IAuthorizationRequirement.
This requirement checks that the user is authenticated and has the claim “MonsterTypeClaim” = “Good”