Secure Asp.Net Core API using Custom Authentication

Secure Asp.Net Core Web API Application using custom credentials (Username and Password)

September 16, 2020

In this article we will cover how to secure Asp.Net Core API using custom authentication i.e using credentials (username and password)

appsettings.json

Copy below mentioned code and replace it with existing code in appsettings.json.

{
  "Logging": {
    "LogLevel": {
      "Default""Information",
      "Microsoft""Warning",
      "Microsoft.Hosting.Lifetime""Information"
    }
  },
  "APIUsername""user-hpblogs",
  "APIPassword""password-hpblogs"
}

AuthenticationMiddleware.cs

Create a Middleware class at root level named "AuthenticationMiddleware.cs" and replace it's code with the code given below.

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Text;
using System.Threading.Tasks;
 
namespace HpBlogs
{
    public class AuthenticationMiddleware
    {
        private readonly RequestDelegate _next;
        private IConfiguration configuration;
 
        public AuthenticationMiddleware(RequestDelegate nextIConfiguration iConfig)
        {
            _next = next;
            configuration = iConfig;
        }
 
        public async Task Invoke(HttpContext context)
        {
            string authHeader = context.Request.Headers["APIAuthentication"];
            if (authHeader != null)
            {
                string base64encodedUsernamePassword = authHeader;
                Encoding encoding = Encoding.GetEncoding("iso-8859-1");
                string usernamePassword = encoding.GetString(Convert.FromBase64String(base64encodedUsernamePassword));
 
                int seperatorIndex = usernamePassword.IndexOf(':');
 
                var username = usernamePassword.Substring(0, seperatorIndex);
                var password = usernamePassword.Substring(seperatorIndex + 1);
 
                string APIUsername = configuration.GetValue<string>("APIUsername");
                string APIPassword = configuration.GetValue<string>("APIPassword");
 
                if (username == APIUsername && password == APIPassword)
                {
                    await _next.Invoke(context); //Authorized
                }
                else
                {
                    context.Response.StatusCode = 401; //Unauthorized
                    return;
                }
            }
            else
            {
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }
    }
}

Startup.cs

Register AuthenticationMiddleware inside Configure Method as shown below.

public void Configure(IApplicationBuilder appIWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
 
    app.UseRouting();
 
    app.UseMiddleware<AuthenticationMiddleware>();
 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Now the API is secure by providing credentials. For access API we need to pass provided credentials in Request Header.

If credential passed in the header matches, then the API will run else it will give Unauthorized access error.

Access / Call API using HttpClient

using System;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.Net.Http.Headers;
 
namespace HpBlogs.Controllers
{
    public class CityController : Controller
    {
        public ActionResult Index()
        {
            string _apiBaseURI = "https://localhost:44382/api/";
 
            string APIUsername = "user-hpblogs";
            string APIPassword = "password-hpblogs";
            var byteArray = Encoding.ASCII.GetBytes($"{APIUsername}:{APIPassword}");
 
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(_apiBaseURI);
            client.DefaultRequestHeaders.Add("APIAuthentication"Convert.ToBase64String(byteArray));
 
            var res = client.GetAsync($"City").Result;
            if (res.IsSuccessStatusCode && res.StatusCode.ToString().ToLower().Equals("ok"))
            {
 
            }
            return View();
        }
    }
}

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...