Implement Basic Authentication In Asp.Net Web Api

Basic authentication sends additional information in every HTTP request, using basic authentication, we would pass the user’s credentials or the authentication token in the header of the HTTP request. That header information will be checked at the server side. If the information sent in header is correct then it will give 200 OK as response, if not then it will give 401 unauthorised access as response.
Following the code sample of HTTP Basic Authentication:
Step 1: Create Helper Class for Basic Authentication

using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
 
namespace ApiServer.Helper
{
    /// <summary>
    /// Purpose: This class is used for authencation of HTTP request by end user.
    /// </summary>
    public class BasicAuthentication : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                ///Below Authentication Token Recieved Whenever User Communicate With HTTP POST Request
                ///This Header Information Will Be There In Every HTTP POST Request
                var authenticationToken = "9DCA8F18-C15F-44A7-8F33-63DBD363578D";
 
                ///Check Whether The Authentication Token Is Valid Or Not
                if (HttpContext.Current.Request.HttpMethod == "POST" && !request.Headers.Contains("AuthenticationToken"))
                {
                    return new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent("Invalid Header: Please provide valid header information.")
                    };
                }
 
                if (request.Headers.Contains("AuthenticationToken"))
                {
                    ///If User HTTP Request Header information Does Not Match With Provided Token
                    ///Then They Will Not Allows To Get Any Information In Any HTTP POST Request
                    if (request.Headers.GetValues("AuthenticationToken").FirstOrDefault() != authenticationToken)
                    {
                        return await Task.Factory.StartNew(() =>
                        {
                            return new HttpResponseMessage(HttpStatusCode.BadRequest)
                            {
                                Content = new StringContent("Invalid Security Token.")
                            };
                        });
                    }
                    else
                    {
                        return await base.SendAsync(request, cancellationToken);
                    }
                }
 
                return await base.SendAsync(request, cancellationToken);
            }
            catch (System.InvalidOperationException ex)
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(ex.Message)
                };
            }
        }
    }
}


Step 2: Register above Basic Authentication Handler in Global Class

using System;
using System.Web.Http;
 
namespace ApiServer
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
 
            GlobalConfiguration.Configuration.MessageHandlers.Add(new Helper.BasicAuthentication()); // Register Handler
        }
    }
}

Comments

Popular posts from this blog

How To Detect Listview Scroll State (Idle/Running) In Xamarin.Forms?

How To Upload And Save Image Or File Using Asp.Net WebApi? – Server Side (Part 1)

Generic Web Api Client Request (GET/POST)