21 Mar, 2017

Testing Authorization Handlers in ASP.NET Core

In one of my previous blog post around this area. I spoke about how you can assert authorization based on the calling user context upon a particular resource. There are many different kinds of ways to do Authorization in ASP.NET Core,. The “ways in which you can do authorization” spectrum goes from simple authorization, all the way to resource based authorization and anything in-between.

Some people (1,2) disagree with some of the out of the box approaches that Microsoft have given us in order to do authorization in a sane manner. However, I do believe that resource based authorization in ASP.NET Core allows you to make this grey area even more grey. The basic notion of resource based authorization in ASP.NET Core goes as follows:

F(C,R,O) => {true, or false}

Where:

F is the function responsible for saying weather authorization has been challenged or not.
C is the calling context that defines the space within which the authorization is taking place.
R is the resource, the resource is typically something important with respect to the application, It may or may not be some sort of authorization model based off of the domain model.
O is the operation or action that wants to be applied to resource R.

Authorization Handlers in ASP.NET core work exactly like the function described above but how does it work? Well…

Lets say that we are building an API for a forum. And the domain rules dictate that only the owner/creator of the post can edit and delete the post. We can define our operations O as follows:

Then we can image a simple model for our domain object (which is a forum post) too look like this:

The model for the domain object can be used to construct R the authorization model or resource:

Then we can construct our function F which is an AuthorizationHandler in ASP.NET Core:

If you have ever used authorization handlers, they might end up in your controllers looking like something like this And then finally to test this we can start with testing our handler:

Basically we arrange the test by making a mock resource (R) called authorizationModel, we also construct a user with a given subject claim (the sub or subject claim is the userId) (C), and then we then specify what operation O we want to apply on resource R. We invoke the function and then make an assertion on the authorizationHandler (F) to see whether it was successful or not.

And to test what happens if an invalid user tries to delete a resource that does not belong to them we can test it like this:

A full comprehensive sample of this can be found at my repo here.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *