HTTP Message Handler in Web API: Implement Authentication Using Custom Message Handler

This is the “HTTP Message Handler in Web API” article series. In our previous articles we have learned various concepts of custom HTTP Message Handlers. You can read them here.

In this article, we will implement an authentication process using a custom Message Handler. We all know that an authentication is the process of the user proving her credentials before accessing the system. When we log onto our computer, we provide our credentials to let the system know who I am. And whether I am able to prove myself that I am indeed who I say I am.

In a service based application authentication plays a vital role in terms of security implementation. One service based application might run anywhere in any hardware box and it don’t know about its client. There is a great chance of unauthorized access if anyone knows the service URL (or RESTFul URL in API).

To prevent the unauthorized access we can implement our own authentication process.

Though there are many ways to perform the authentication process, in this article we will implement a token verification system to authenticate users.
The step of operation is as in the following.

The client will send an authentication token in the header of a HTTP request and in the custom Message Handler we will check whether the user has sent the proper authentication token or not. If the authentication token is OK then we will allow the request to reach the target controller otherwise we will return our own response message.

So, let’s implement it practically.

Step 1: Create client application that will send the GET request to the API

Here is a sample implementation of an ajax() client that will perform the GET request to the Values controller. The important part of this example is the beforeSend() callback function where we are inserting a token value to the HTTP request.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWEB_API.WebForm1" %>  
  2. <head id="Head1" runat="server">  
  3. <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>  
  4. <script>  
  5.     $(document).ready(function () {  
  6.         $.ajax({  
  7.             url: 'http://localhost:11129/api/values',  
  8.             type: 'GET',  
  9.             dataType: 'json',  
  10.             success: function (data, textStatus, xhr) {  
  11.                 console.log(JSON.stringify(data));  
  12.             },  
  13.             error: function (xhr, textStatus, errorThrown) {  
  14.                 console.log(xhr);  
  15.             },  
  16.             beforeSend: function (xhr) {  
  17.                 xhr.setRequestHeader("Authorization""Mytoken");  
  18.             }  
  19.         });  
  20.     });  
  21. </script>  
  22. </head>  
  23. <body>  
  24. </body>  
  25. </html> 

For the sake of simplicity we did not encode the token value, but in a real scenario we should use some encoding mechanism before sending a token value through a HTTP request to protect us from packet sniffing or some other type of attack.

Fine, we have done our client-side implementation. Now we will move to the Web API part where we will configure a custom Message Handler to check the HTTP header.

Step 2: Implement custom Message Handler

It's now time to implement the custom Message Handler, to check the authentication token from the HTTP header. Have a look at the following code. This is the complete code of my Global.asax page.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Threading;  
  8. using System.Threading.Tasks;  
  9. using System.Web;  
  10. using System.Web.Http;  
  11. using System.Web.Http.Filters;  
  12. using System.Web.Http.WebHost;  
  13. using System.Web.Mvc;  
  14. using System.Web.Optimization;  
  15. using System.Web.Routing;  
  16. using System.Web.SessionState;  
  17. namespace TestWEB_API  
  18. {  
  19.     public class WebApiApplication : System.Web.HttpApplication  
  20.     {  
  21.         protected void Application_Start()  
  22.         {   
  23.             WebApiConfig.Register(GlobalConfiguration.Configuration);  
  24.             GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageHandler1());   
  25.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  26.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  27.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
  28.         }  
  29.     }   
  30.     public class MessageHandler1 : DelegatingHandler  
  31.     {  
  32.            protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
  33.            {  
  34.                string token;  
  35.                try  
  36.                {  
  37.                    token = request.Headers.GetValues("Authorization").FirstOrDefault();  
  38.                    if (token != "Mytoken")  
  39.                    {  
  40.                        //Code for authenticate user. We got authentication ticket  
  41.                            return await Task.Factory.StartNew(() =>  
  42.                            {  
  43.                                return new HttpResponseMessage(HttpStatusCode.BadRequest)  
  44.                                {  
  45.                                    Content = new StringContent("sorry !! you are not authentic user")  
  46.                                };  
  47.                            });  
  48.                    }  
  49.                    else  
  50.                    {  
  51.                        return await base.SendAsync(request, cancellationToken);  
  52.                    }  
  53.                }  
  54.                catch (System.InvalidOperationException)  
  55.                {  
  56.                    return null;  
  57.                }  
  58.            }  
  59.     }  
  60. } 

We are trying to get the value from the HTTP header with the key “ Authorization”.

If the value of the “Authorization” key is “Mytoken” then we will consider the request as a valid request, otherwise it’s a forbidden request.

Now, again for the sake of simplicity we did not implement any validation logic with the DB or any persistent storage media. We are just checking with a string constant. In a real application most probably you need to write logic to verify with the database.

Step 3: Implement Get() action with controller

We will now implement one Get() action that we will call using the ajax() function. Here is sample code for that.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web;  
  7. using TestWEB_API.Models;  
  8. using System.Web.SessionState;  
  9. using System.Web.Http;  
  10. using System.Web.Mvc;  
  11. namespace TestWEB_API.Controllers  
  12. {  
  13.     public class ValuesController : ApiController  
  14.     {  
  15.         //api/Get  
  16.         public string[] Get()  
  17.         {  
  18.             return new string[] {"Sourav","Kayal" };  
  19.         }  
  20.     }  
  21. } 

And we are getting the value from the Get() action within the ajax() success callback.

Get Action with Controller

Cheers! We got data from the API after successful verification. We will now change the value of the authentication token and again we will perform the same GET request to the same controller. Have a look at the beforeSend() method where we have changed the value of the Authorization key.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWEB_API.WebForm1" %>  
  2. <head id="Head1" runat="server">  
  3. <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>  
  4. <script>  
  5.     $(document).ready(function () {  
  6.         $.ajax({  
  7.             url: 'http://localhost:11129/api/values',  
  8.             type: 'GET',  
  9.             dataType: 'json',  
  10.             success: function (data, textStatus, xhr) {  
  11.                 console.log(JSON.stringify(data));  
  12.             },  
  13.             error: function (xhr, textStatus, errorThrown) {  
  14.                 console.log(xhr);  
  15.             },  
  16.             beforeSend: function (xhr) {  
  17.                 xhr.setRequestHeader("Authorization""Mytoken123");  
  18.             }  
  19.         });  
  20.     });  
  21. </script>  
  22. </head>  
  23. <body>  
  24. </body>  
  25. </html> 

And we are getting this XHR response. We are getting our custom HTTP response (bad request) or instead of the Bad request we could send unauthorized access, or anything.

XHR response

Conclusion

In this article, we have learned to implement an “Authentication” process using the Web API. I hope you have learned it. In the future, in a few more articles we will learn a few more interesting concepts of this.


Similar Articles