How to secure Web APIs using authorization filters

Take advantage of authorization filters to authorize incoming requests to your Web API

Web API Security

Web API Security

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 procedures you can adopt 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 it is with authorization filters.

Using AuthorizeAttribute

Ideally, you should perform authentication and authorization earlier in the Web API pipeline. This would ensure that the unnecessary processing overhead of the request cycle is eliminated. Note that the authorization filters execute before the controller action methods. So if the incoming request is not authorized, an error would be returned from the service, the request is ignored, and the action method of the service is not executed. Note that you can retrieve the current principal from the ApiController.User property.

The built-in authorization filter AuthorizeAttribute can be used to authorize incoming requests. You can authorize a user using this attribute and return the HTTP status code 401, meaning that the request is not authorized. The 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());

        } 

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 }

}

It is also possible restrict access to action methods by roles and users. The following code listing 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

}

Refer to the code snippet given earlier. The Employees controller restricts access to the users Joydip and Jini only. The following code listing 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 take your decision depending the user's role. This is shown in the code listing shown given next.

public HttpResponseMessage Get()

{

    if (User.IsInRole("Administrators"))

    {

        //Write your code here

    }

}

Using custom Authorization Filters

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 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;

        }

    }

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.