How to secure ASP.Net Web APIs using authorization filters

Take advantage of ASP.Net Web API authorization filters to authorize incoming requests to your web API

How to secure ASP.Net Web API using authorization filters
Thinkstock

Security is a major concern in web-based enterprise applications. When you need to transmit data over the wire, you should be aware of the various tools you can use to secure that data.

ASP.Net Web API is a lightweight framework used for building stateless RESTful services that run on HTTP.  One way to secure Web API services is with authorization filters.

Ideally, you should perform authentication and authorization early in the Web API pipeline. This helps to eliminate unnecessary processing overhead from the request cycle. Note that, whether you use HTTP modules or HTTP message handlers for authentication, you can retrieve the current principal (i.e. the user) from the ApiController.User property.

Also keep in mind that Web API authorization filters execute before the controller action methods. So if the incoming request is not authorized, an error will be returned from the service, the request will be ignored, and the action method of the service will not be executed.

Using the AuthorizeAttribute authorization filter

The built-in authorization filter AuthorizeAttribute can be used to authorize incoming requests. You can use AuthorizeAttribute to check whether the user is authenticated. If the user is not authenticated, it will return the HTTP status code 401. This authorization can be applied in Web API globally or at the controller level.

Note that you can also implement a custom message handler to authorize access to your controller methods as message filters are executed much earlier in the Web API life cycle.

To restrict access to all controllers, you can add the AuthorizeAttribute globally to the Filters collection of the HttpConfiguration instance. The following code snippet shows how you can add the AuthorizeAttribute to the Filters collection of the HttpConfiguration object.

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services 
            // Web API routes
            config.MapHttpAttributeRoutes(); 
            config.Routes.MapHttpRoute(
                name: “DefaultApi”,
                routeTemplate: “api/{controller}/{id}”,
  
              defaults: new { id = RouteParameter.Optional }
            ); 
            config.Filters.Add(new AuthorizeAttribute());
        } 

Using the Authorize attribute 

At the controller level, you can restrict access by applying the Authorize attribute as shown in the code snippet given next.

[Authorize]
public class EmployeesController : ApiController
{
    //Write methods here that correspond to the Http verbs
}

You can also apply the Authorize attribute at the action level to restrict access to a particular action method. The following code snippet illustrates how this can be implemented.

public class EmployeesController : ApiController
{
    public HttpResponseMessage Get() { //Some code }
   // Require authorization for a specific action.
    [Authorize]
    public HttpResponseMessage Post(Employee emp) { //Some code }

In the code snippet shown earlier, access to the Post() method is restricted while access to the Get() method is not restricted. You can also restrict the controller and then provide anonymous access to one or more action methods. The code snippet that follows illustrates this.

public class EmployeesController : ApiController
{
    public HttpResponseMessage Get() { //Some code }
    [AllowAnonymous]
    public HttpResponseMessage Post(Employee emp) { //Some code }
}

Authorize actions by roles and users

It is also possible to restrict access to action methods by roles and users. The following code snippet shows how this can be achieved.

[Authorize(Users="Joydip,Jini")] //Restrict access by user
public class EmployeesController : ApiController
{
   //Write methods here that correspond to the Http verbs
}

In the above example, the Employees controller restricts access to the users Joydip and Jini only. The code below shows how you can restrict access by roles.

[Authorize(Roles="Administrators")] //Restrict by roles
public class EmployeesController : ApiController
{
    //Write methods here that correspond to the Http verbs
}

You can always access the ApiController.User property inside the controller method to retrieve the current principle and grant authorization based on the user’s role. This is shown in the code listing below.

public HttpResponseMessage Get()
{
    if (User.IsInRole(“Administrators”))
    {
        //Write your code here
    }
}

Using custom authorization filters in ASP.Net Web API

An authorization filter is a class that extends the AuthorizationFilterAttribute class and overrides the OnAuthorization() method. This is the method where you can write the authorization logic. If the authorization fails you can return an instance of the UnauthorizedException class or even a custom HttpResponseMessage.

The following code listing shows how you can implement a custom class for authorizing requests to your web API. Note that you should extend the AuthorizeAttribute class to implement your own authorization filter class.

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
         public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (AuthorizeRequest(actionContext))
            {
                return;
            }
            HandleUnauthorizedRequest(actionContext);
        }
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
           //Code to handle unauthorized request
        }
        private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //Write your code here to perform authorization
            return true;
        }
    }

Copyright © 2017 IDG Communications, Inc.

How to choose a low-code development platform