Basic Authentication with Middleware in ASP.NET Core 3 Web API

On the Visual Studio, create new ASP.NET Core Web Application project

Input Project Name and select Project Location




Select Empty Template and click Create button to Finish

Structure of New Project




Create new folder named Middlewares. In this folder, create new middlewares as below:

In Middlewares folder, create new class named BasicAuthMiddleware.cs as below:

using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace LearnASPNETCore3WebAPIWithRealApps.Middlewares
{
    public class BasicAuthMiddleware
    {
        private readonly RequestDelegate _next;

        public BasicAuthMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            string authHeader = httpContext.Request.Headers["Authorization"];
            if (authHeader != null)
            {
                string auth = authHeader.Split(new char[] { ' ' })[1];
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                var usernameAndPassword = encoding.GetString(Convert.FromBase64String(auth));
                string username = usernameAndPassword.Split(new char[] { ':' })[0];
                string password = usernameAndPassword.Split(new char[] { ':' })[1];
                if (username == "abc" && password == "123")
                {
                    await _next(httpContext);
                }
                else
                {
                    httpContext.Response.StatusCode = 401;
                    return;
                }
            }
            else
            {
                httpContext.Response.StatusCode = 401;
                return;
            }
        }
    }

    public static class BasicAuthMiddlewareExtensions
    {
        public static IApplicationBuilder UseBasicAuthMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<BasicAuthMiddleware>();
        }
    }
}




Open Startup.cs file and add new configurations as below:

using LearnASPNETCore3WebAPIWithRealApps.Middlewares;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCore3WebAPIWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware<BasicAuthMiddleware>();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Create new folder named Controllers. In this folder, create new controller named DemoController.cs as below:

using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DemoASPNETCore3WebAPI.Controllers
{
    [Route("api/demo")]
    public class DemoController : Controller
    {
        [Produces("text/plain")]
        [HttpGet("demo1")]
        public async Task<IActionResult> Demo1()
        {
            try
            {
                var content = "Hello World";
                return Ok(content);
            }
            catch
            {
                return BadRequest();
            }
        }

        [Produces("text/html")]
        [HttpGet("demo2")]
        public async Task<IActionResult> Demo2()
        {
            try
            {
                var content = "<b><i><u>Hello World</u></i></b>";
                return new ContentResult
                {
                    Content = content,
                    ContentType = "text/html",
                    StatusCode = (int)HttpStatusCode.OK
                };
            }
            catch
            {
                return BadRequest();
            }
        }

    }
}




Access Demo1 action in Demo controller without use account: http://localhost:48982/api/demo/demo1

Access Demo2 action in Demo controller without use account: http://localhost:48982/api/demo/demo2

Access Demo2 action in Demo controller with invalid account: http://localhost:48982/api/demo/demo2

Access Demo2 action in Demo controller with valid account: http://localhost:48982/api/demo/demo2




Create Console App (.NET Framework) Project in Visual Studio.

DemoRestClientModel class contain methods call Web API

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps_Client
{
    public class DemoRestClientModel
    {
        private string BASE_URL = "http://localhost:18942/api/demo/";

        public Task<HttpResponseMessage> Demo1()
        {
            try
            {
                HttpClient client = new HttpClient();
                var authInfo = Convert.ToBase64String(Encoding.Default.GetBytes("abc:123"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
                client.BaseAddress = new Uri(BASE_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
                return client.GetAsync("demo1");
            }
            catch
            {
                return null;
            }
        }
    }
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            DemoRestClientModel demoRestClientModel = new DemoRestClientModel();

            HttpResponseMessage httpResponseMessage = demoRestClientModel.Demo1().Result;

            HttpStatusCode httpStatusCode = httpResponseMessage.StatusCode;
            Console.WriteLine("Status Code: " + httpStatusCode);

            bool isSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode;
            Console.WriteLine("IsSuccessStatusCode: " + isSuccessStatusCode);

            string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
            Console.WriteLine("Result: " + result);

            Console.ReadLine();
        }
    }
}
Status Code: OK
IsSuccessStatusCode: True
Result: Hello World