Part 1 - Configuring Enforcer
In this part of the tutorial you will bring Enforcer into the project and initialize it during startup. This will put a set of artifacts into the IoC container that can then be used to provide authorization.
Adding Enforcer to the project
Go to the Nuget package manager and install the latest versions of both the Rsk.Enforcer
and Rsk.Enforcer.AspNetCore
packages into the WebApiTutorial
project. Enforcer is now ready to start configuring - remember to have your license key to hand.
Configuring Enforcer
At the top of Startup.cs
is a Constants
class. Use your demo license key for the LicenseKey
member.
In the Startup.cs
file, ConfigureServices
calls a, currently empty, method called ConfigureAuthorization
passing the services collection. You will add your enforcer configuration here using a fluent API to provide the configuration. You will use the following methods:
AddEnforcer
: to provide the main bootstrapAddEmbeddedPolicyStore
: to state that the policies are embedded in the Policy folderAddPolicyEnforcementPoint
: to define how you want Enforcer to behave if the outcome of the policy cannot be determinedAddDefaultAdviceHandling
: to log advice produced by polict evaluationAddClaimsAttributeProvider
: to allow the identity claims to be used inside the policy
private void ConfigureAuthorization(IServiceCollection services)
{
services.AddEnforcer("AcmeQuotes.ReadQuotes", o =>
{
o.Licensee = Constants.Licensee;
o.LicenseKey = Constants.LicenseKey;
})
.AddEmbeddedPolicyStore("WebApiTutorial.Policy")
.AddPolicyEnforcementPoint(o => o.Bias = PepBias.Deny)
.AddDefaultAdviceHandling()
.AddClaimsAttributeValueProvider(o => { });
}
In the call to AddEnforcer
, AcmeQuotes.ReadQuotes
is the fully qualified name of the root policy that we will be executing for the application. We will be adding a ReadQuotes
policy inside an AcmeQuotes
namespace. This could be a policy set containing many policies but in this case it will be a single policy with a small number of rules.
The policy store points to resources embedded in the Policy
folder. It is here, in the next part, we shall start to define our authorization rules.
Enforcer is now configured, and so next we make it start enforcing policy.