Basic Authentication Using Message Handlers In Web API

In order to perform authentication of Web API, we can use basic authentication. This authentication can either be performed by using HTTP handlers or by using the message handlers. Both handler types are different but message handlers are more specific to the Web APIs. In this article, we will see how we can use the message handlers to perform the basic authentication of the user. 
 
To start with, we will create a blank solution and add a new project of type Web API. Next, we add a Web API type Controller and add a simple method GetData that will take input an integer value and return a string. So, the  Web API will look like the following.
  1. public class TestController : ApiController  
  2.     {  
  3.         public string GetData(int Id)  
  4.         {  
  5.             return ("You entered: " + Id);  
  6.         }  
  7.     }  
Next, we will create a new message handler. We add a new class named MessageHandlerAuthentication and derive it from DelegatingHandler type class. This class contains a virtual method of the following type. 
  1. public class MessageHandlerAuthentication : DelegatingHandler  
  2.    {  
  3.        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
  4.        {  
  5.            
  6.        }  
  7.    }  
In Web API, before a request reaches the Controller, it has to pass through a series of message handlers. Our custom handler that we added above will also be one of the same types and will get added into the request pipeline. So, before the request reaches Controller, this handler will be executed and the SendAsync method above will contain the logic to validate the request. If successfully validated, the request will be allowed to further passed to the next handler in the pipeline, by "base.SendAsync" method call in the above method.
 
When the request is validated successfully, we need to attach an IPrincipal type object to the current Thread and current HttpContext. So we add a new class named CustomPrincipal and derive it from IPrincipal. We also add a new property named UserRole to keep the current users' role in it. Now, the code will look like the following,
  1. public class CustomPrincipal : IPrincipal  
  2.    {  
  3.        public CustomPrincipal(string userName)  
  4.        {  
  5.            UserName = userName;  
  6.            Identity = new GenericIdentity(userName);  
  7.        }  
  8.   
  9.        public string UserName { getset; }  
  10.        public IIdentity Identity { getset; }  
  11.        public bool IsInRole(string role)  
  12.        {  
  13.            if (role.Equals("user"))  
  14.            {  
  15.                return true;  
  16.            }  
  17.            else  
  18.            {  
  19.                return false;  
  20.            }  
  21.        }  
  22.    }  
Next, we will add the custom validation logic. Since we are using basic authentication, we will add a method which will read the authorization header and validate the credentials provided. If the credentials are valid, then it will set the IPrincipal object in the current thread and current http context. So, the code will look like the following.
  1. public class MessageHandlerAuthentication : DelegatingHandler  
  2.   {  
  3.       string _userName = "";  
  4.   
  5.       private bool ValidateCredentials(AuthenticationHeaderValue authenticationHeaderVal)  
  6.       {  
  7.           try  
  8.           {  
  9.               if (authenticationHeaderVal != null && !String.IsNullOrEmpty(authenticationHeaderVal.Parameter))  
  10.               {  
  11.                   string[] decodedCredentials = Encoding.ASCII.GetString(Convert.FromBase64String(authenticationHeaderVal.Parameter)).Split(new[] { ':' });  
  12.   
  13.                   if (decodedCredentials[0].Equals("jasminder") && decodedCredentials[1].Equals("jasminder"))  
  14.                   {  
  15.                       _userName = "Jasminder Singh";  
  16.                       return true;  
  17.                   }  
  18.               }  
  19.               return false;  
  20.           }  
  21.           catch  
  22.           {  
  23.               return false;  
  24.           }  
  25.       }  
  26.   
  27.       protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
  28.       {  
  29.           if (ValidateCredentials(request.Headers.Authorization))  
  30.           {  
  31.               IPrincipal principal = new GenericPrincipal(new GenericIdentity("Jasminder Singh"), new string[] { "Admin" });  
  32.               Thread.CurrentPrincipal = principal;  
  33.               HttpContext.Current.User = principal;  
  34.           }  
  35.   
  36.           var response = await base.SendAsync(request, cancellationToken);  
  37.           if (response.StatusCode == HttpStatusCode.Unauthorized && !response.Headers.Contains("WwwAuthenticate"))  
  38.           {  
  39.               response.Headers.Add("WwwAuthenticate""Basic");  
  40.           }  
  41.   
  42.           return response;  
  43.       }  
  44.   }  
Now, we will add the message handler to the Web API pipeline, using the following code in the Register method of WebApiConfig.cs file. 
  1. public static void Register(HttpConfiguration config)  
  2.        {  
  3.            // Web API configuration and services  
  4.   
  5.            // Web API routes  
  6.            config.MapHttpAttributeRoutes();  
  7.   
  8.            config.Routes.MapHttpRoute(  
  9.                name: "DefaultApi",  
  10.                routeTemplate: "api/{controller}/{id}",  
  11.                defaults: new { id = RouteParameter.Optional }  
  12.            );  
  13.   
  14.            GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageHandlerAuthentication());  
  15.        }  
The authentication mechanism is in place but we also need to make sure that the method does not get hit, if the credentials are not valid. To do this, we will add the Authorize attribute on the controller method. If the credentials are not valid, the request will not hit the method.
  1. public class TestController : ApiController  
  2.    {  
  3.        [Authorize]  
  4.        public string GetData(int Id)  
  5.        {  
  6.            return ("You entered: " + Id);  
  7.        }  
  8.    }  
Run the application and make a request using Postman app. The request will first hit the message handler and if validated, will further call the method; else, it will return http status code 401 un-authorized message.

 
Further, in order to set the authorization based on roles, we just need to add the role names in the authorize attribute. While generating the IPrincipal object, we already provided the role name. So, when the Controller method is to be called, the role specified in authorize attribute is verified against the role we provided in the IPrincipal object. 
  1. public class TestController : ApiController  
  2.   {  
  3.       [Authorize(Roles = "Admin")]  
  4.       public string GetData(int Id)  
  5.       {  
  6.           return ("You entered: " + Id);  
  7.       }  
  8.   }  
So, this was about basic authentication using message handler in Web API. Hope you enjoyed reading it. Happy coding...!!!

Up Next
    Ebook Download
    View all
    Learn
    View all