Authorize ASP.NET Web API using Basic Authorization Header

Secure or Authorize ASP.NET Web APIs using Basic Authorization Header

March 20, 2021

In this article we will cover how to Secure or Authorize ASP.NET Web APIs using Basic Authorization Header.

The API will be secure using username and password.

Eevery api request should have this authentication as part of authorization header.

Web.config

Add below mentioned key inside "appSettings" and change the value based on your project.

below are the steps to impelement API Authorization

    <add key ="apiusername" value="your apiusername"/>
    <add key ="apipassword" value="your apipassword"/>

BasicAuthenticationWithHeaders.cs

Create BasicAuthenticationWithHeaders.cs class inside any folder or at root level and replace the code with given below.

using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
 
namespace Hpblogs
{
    public class BasicAuthenticationWithHeaders : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                string requestAuthorization = actionContext.Request.Headers.Authorization.Parameter;
                string strAuthorization = Encoding.UTF8.GetString(Convert.FromBase64String(requestAuthorization));
 
                string reqUsername = strAuthorization.Split(':')[0];
                string reqPassword = strAuthorization.Split(':')[1];
 
                string apiusername = ConfigurationManager.AppSettings["apiusername"];
                string apipassword = ConfigurationManager.AppSettings["apipassword"];
 
 
                if (apiusername.Equals(reqUsername) && apipassword.Equals(reqPassword))
                {
                    //Successful Authentication
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
 
            base.OnAuthorization(actionContext);
        }
    }
}

WebApiConfig.cs

Register above mentioned class inside "App_Start/WebApiConfig.cs" file as mentioned below.

using System.Web.Http;
 
namespace HpBlogs
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
 
            config.Routes.MapHttpRoute(
                name"DefaultApi",
                routeTemplate"api/{controller}/{action}/{id}",
                defaultsnew { id = RouteParameter.Optional }
            );
 
            config.Filters.Add(new BasicAuthenticationWithHeaders());
        }
    }
}

Your API is now seacure with Basic Authorization header i.e apiusername and apipassword.

Below is the code which consume the api using Http Web Request in Asp.net

string encodedCred = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("your apiusername" + ":" + "your apipassword"));
 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:65123/api/Currency");
request.Method = "GET";
request.Headers.Add("Authorization""Basic " + encodedCred);
request.ContentType = "application/x-www-form-urlencoded";
 
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...