Basic HTTP Authentication in ASP.NET MVC4 WEB API 2 using message handler

In this article, I will walk you through series of steps to secure your ASP.NET WEB API 2 HTTP requests using HTTP Message Handlers. In this way, we will make sure requests Posted to your WEB API controller in MVC4 is authenticated in a secure manner.

As you all know, HTTP Message handler is just a class to handle HTTP requests that comes in and returns back HTTP response.

When you are ready with your MVC4 website application with WEB API controller actions for background processing, this article comes in handy for you to implement basic HTTP authentication using message handler.

we will be using DelegatingHandler inbuilt class to inherit our BasicAuthMessageHandler class. This way the message handlers are chained together to handle HTTP requests and responses serially.

Here is the series of steps with code snippets to implement this functionality.

1. Create a public class called Credentials.cs to declare username and password of type string.


2. Create a public interface called IProvidePrincipal.cs to check credentials. Please make sure to use required namespaces as shown in the screenshot below. IPrincipal interface used to create method CreatePrincipal defines the basic functionality of Principal object.


3.Create a public class called PrincipalProvider.cs to set User Id and Password from your Web.Config for Authentication.


4. Create a public class called BasicAuthMessageHandler to handle authentication requests.
Please refer below screenshots for declarations and methods used. There are two methods used. one is SendAsync to handle requests and another one is ParseAuthorizationHeader of type Credentials we already created.


SendAsync method


5. Add below code snippet in Global.asax Application_start()

.MessageHandlers.Add(new BasicAuthMessageHandler()
PrincipalProvider = new PrincipalProvider()

6. Make sure to add authentication keys in appsettings in web config.

Thats it!! Now when you send a HTTP request to web API controller action using any client (RESTClient), your request would be authenticated by popping up a username/password dialog.

Hope this article helps you!

Thank you,


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: