There are so many ways to secure the Web API. But in this post we will see the Authentication process using “Message Handler”.
As we know in asp.net Web API, before execution of any controller, Httprequest go through the message Handler pipeline sequence as given below image

So if we have to implement the some custom validation logic, it will be better to write code in Message Handler.
What is the Message Handler in asp.net Web API ?
>> A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.
There will be series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain as shown in above image. This pattern is also called a delegating handler.
How to write the Custom Message Handler ?
So many time we will get the scenario to write our own logic in Message Handler to perform some specific task on that scenario we have to create Custom Message handler.
To write the Custom Message Handler we have to
1. Inherit the System.Net.Http.DelegatingHandler
2. Override SendAsync Method of HttpMessageHandler as given below
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Here will be our own login
}
How to implement Custom Authentication process in Message Handler ?
>> From client side we can pass the some Key and Value as Authentication Token. As we know before execution of API controller it will go through the message handler pipeline so in Message handler we have to validate the given Token Value, if it is correct then further execution will happen else we will send the Forbidden request
Step 1: Create some class like APIKeyHandler in Some folder like Security
Step 2: Write the logic as given below in APIKeyHandler class
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace WebApi_Sample.Security
{
public class APIKeyHandler : DelegatingHandler
{
//set a default API key
private const string yourApiValue = "API_Sample_Value";
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isValidAPIKey = false;
IEnumerable<string> lsHeaders;
//Validate that the api key exists
var checkApiKeyExists = request.Headers.TryGetValues("Sample_Key", out lsHeaders);
if (checkApiKeyExists)
{
if (lsHeaders.FirstOrDefault().Equals(yourApiValue))
{
isValidAPIKey = true;
}
}
//If the key is not valid, return an http status code.
if (!isValidAPIKey)
return request.CreateResponse(HttpStatusCode.Forbidden, "Sorry you have provide wrong API key.");
//Allow the request to process further down the pipeline
var response = await base.SendAsync(request, cancellationToken);
//Return the response back up the chain
return response;
}
}
}
Note: In the above code DelegatingHandler is abstract class which has overridden the method of HttpMessageHandler Class.
In the above code we are passing the yourApiValue= “API_Sample_Value” and Key =”Sample_Key”
If the given input from client side is correct then it will Allow the request to process further down the pipeline else it will terminate the request.
Step 3: Register the Custom Message Code in the Application_Startmethod of Global.asax file like this
GlobalConfiguration.Configuration.MessageHandlers.Add(new APIKeyHandler());
Step 4: Run the application and Test the Api Controller get method from PostMan Tool

