(C# ASP.NET Core) Basic Authentication in WebApi

Basic Authentication is not encourged by ASP.NET Core because login id and password are sent as plain text in the request header - it's vulnerable to XSRF also. So there are no readymade classes like we have for cookies based authentication. But what if your project still needs to allow basic authentication? Perhaps because your security requirements are not of extreme cutting-edge type? For that case we present a simple solution that helps you protect a web-api with basic authorization. It can be a lot safer with Basic Authentication if your communication is over https, and even better if XSRF measures are taken, which is beyond the scope of this tutorial.
(Rev. 18-Jun-2024)

Categories | About |     |  

Parveen,

A brief primer on basic authentication

Basic authentication is defined in a standard called RFC 2617. You can consider going through mozilla developers documentation for a quick reading and the associated practical aspects.

A user sends a GET request containing an authorization header in the format Basic base64(login:pwd) - login and password are separated by a colon.

The server decodes the header and extracts the login and password, and then authenticates the user. If the authentication succeeds the user is served with his data as 200 OK response. But if the authentication fails then the server responds as 401 Unauthorized with a header WWW-Authenticate of value Basic realm[pronounced relm]="purpose of credentials, usually website domain"

Video Explanation (see it happen!)

Please watch the following youtube video:

Implementation of Basic Authentication

We have done a very crude implementation of basic authentication in the project attached to this tutorial.

Open the solution explorer and locate the program.cs file. Double click to open it! Let's examine the code line by line.


// program.cs file of the attached project 

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder();

builder.Services.AddRazorPages();

var app = builder.Build();

app.MapRazorPages();

app.MapGet("/token", ([FromHeader] String? Authorization, HttpContext ctx) =>
{
    bool isAuthorized = !String.IsNullOrEmpty(Authorization);

    if (isAuthorized)
    {
        // 1. decode base64 Authorization value 
        // 2. extract user:pwd 
        // 3. check user/pwd against database or identity 

        // ASSUMING SUCCESS - it's a tutorial! 
    }

    if (!isAuthorized)
    {
        ctx.Response.Headers
                .Add("WWW-Authenticate", "Basic realm=web api access");

        return Results.Unauthorized();
    }

    return Results.Ok(new { access_token = "response from the server" });
});

app.Run();


The first few lines are the boilerplate code that we are already familiar with.

Then we have a GET web api that receives the Authorization header through parameter binding.

After that a check for the existence of this header is made, followed by extraction of userid and password. Since this is a tutorial we assume a successful verification.

If authentication fails, a www-authenticate header is sent with a 401 response.

And, if authentication succeeds, a 200 OK response is sent along with any data requested by the client side.

Test the Project with Browser

Run the project and send a GET request to the web api /token. This request doesn't send any authorization header so the web api sends a 401 response along with a www-authenticate header. And since the browser supports and understands basic authentication, it presents a login and password box.

Type any values. The server will create a base64 authorization header and make a call. The server accepts the call and responds with a 200 OK response.

Test the Project with http repl

We can test the same project with http repl also. Open visual studio and use the menu Tools > Command Line > Developer Command Prompt to open a command prompt. Type the command httprepl <server address>. This will connect to the server end-point.

see the linked video for screenshots

Next send a get request GET /token without any headers and hit the enter key. We observe that the server responds with a www-authenticate header.

Next make a request with a header. We can send any string for the credentials because this is a tutorial, but in a real project we shall have to send them encoded as base64. Type Set header Authorization "Basic base64_login_pwd" and hit the enter key. This sets the header. After that send a get request GET /token. We verify that the server responds with 200 OK. Thankyou!


This Blog Post/Article "(C# ASP.NET Core) Basic Authentication in WebApi" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.