On ASP.NET Core applications, authorizations are configure on Startup at ConfigureServices method.
So in a simple case of authorization, we can use something like this:
But, if you have the case you need more than one claim to access the same resource, controller for instance, you´ll need to add another require claim to the same policy. This will get you on a AND scenario. This means that ALL RequireClaim must be fulfill by the user in context. As a result, this scenario may not be your goal.
In the perfect scenario, we need the OR scenario to be in consideration, i.e., at least one RequireClaim should be enough to authorize the user in context.
This can be accomplished with Authorization Requirements and Handlers.
You have more than one AD group that should access to the same resource on your application. Different users belong to different AD groups and all this users need access to the named resource.
In the authorization pipeline, we need to validate the user context against all authorized AD groups. This means, if the user in context is in at least one of the AD groups, it should be enough to authorize and give access to the resource.
Making use of Requirement and Handlers available on ASP.NET Core 2.2, you can now dive into a OR scenario.
This solution is based on ASP.NET Core 2.2 with windows authentication in witch, there is a MyFeatureController we want to protect.
Simple put, we create a Requirement like this:
And then an Handler to… you know… handle the requirement. In this case, we are handling/validating a list of AD groups against the user context.
Handler code looks like this:
Next step is to use the both above classes, as base classes to MyFeature Requirement and Handler classes:
Now, the only big step missing, is the configuration on startup.
To do this, first, we need to add the list of AD groups authorized to access the MyFeatureController on the appsettings.json:
And then, configure the authorization service on ConfigureServices at Startup:
After all this setup, we create a custom AuthorizeAttribute with MyFeature Policy. Then we’re good to go to use it on MyFeatureController
Since we added our policy to the Authorization pipeline, we can also use this on razor pages to show/hide features based on user authorizations.
Firstly, we have to inject the AuthorizationService into the Views Engine, and to accomplish this, we need to add this 3 lines in the file _ViewImports.cshtml
Secondly, we can now use the AuthorizationService control what to render on views.
For instance, we added the below code on the index.cshtml of Home:
In conclusion, with Requirement and Handler, we have a lot of flexibility of how we want to authorize our application resources. In this case, we are using windows authentication and AD groups to authorize user access, but, it can be easily other kind of authorization to fulfill your needs.
You can check the full example at github: