Applying security to WebAPI controllers

When using the Reurgency.Common framework, every REST service method requires security permissions to be applied via an attribute on either the method or the class.  This blog post describes how to do that.

First add some USING statements.

using Reurgency.Foundation.WebApi;
using Reurgency.Foundation.WebApi.Filters;

Then add the attribute HandleSecurityTokenRequest to either the class or individual methods

Here is an example of using the attribute on a class. ALL methods in the class will inherit this setting.

[HandleSecurityTokenRequest(AllowAnonymous = false)]
public class EmployeesController : <Employee>
{

That’s it.  You are done.

Read on to understand a little more how this works.

Here is an example of a using the attribute on a method. This is useful when you want to set different security on each method within a class.

[HandleSecurityTokenRequest(AllowAnonymous = true)]
[HttpPost]
public HttpResponseMessage Login(Credential credential)
{
BusinessCommandRepository biz = new BusinessCommandRepository(this.securityTokenId, "Login");

As you can see the attribute takes in one parameter called AllowAnonymous.  When set to false the system expects that a valid security token is passed in via headers or cookies.  If a valid security token is not passed in an HTTP Status code of 401 is returned to the client.   When AllowAnonymous is set to true, then the system will first look for a valid security token in the header or cookies and use that, else it will use the constant defined in Reurgency.Common.Model.Entities.SecurityToken.ANONYMOUSSECURITYTOKEN.

Each WebAPI method is responsible for instantiating the BusinessCommandRepository.  The constructor for that class requires a security token.  Simply use this.securityTokenId.

BusinessCommandRepository biz = new BusinessCommandRepository(this.securityTokenId, "Login");

The securityTokenId property is part of Reurgency.Foundation.WebApi.WebApiController.  Every one of your WebAPI controllers should inherit from this class.

It is the responsibility of the HandleSecurityTokenRequest filter attribute to populate this.securityTokenId from either header, cookies, or ANONYMOUSSECURITYTOKEN.  Because the filters are processed PRIOR to the WebAPI method’s execution, you are guaranteed that this.securityTokenId will be populated or a 401 error will be thrown.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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