Skip to main content

Implementing Basic Authentication

Implementing Basic Authentication in ASP.NET Core Web API

What is Basic Authentication?

Basic Authentication is a type of authentication scheme used to provide a secure way for clients to access protected endpoints on a web server. It is the simplest form of authentication and is based on a username and password combination.

Advantages of Basic Authentication

  • It is simple to use and setup.
  • It is secure as it requires a username and password for authentication.
  • It is widely supported by web browsers.

Disadvantages of Basic Authentication

  • It is vulnerable to man-in-the-middle attacks.
  • It is not recommended for use over an unencrypted connection.
  • The username and password can be easily guessed.

Implementing Basic Authentication in ASP.NET Core Web API

Step 1: Configure Authentication

The first step is to configure the authentication middleware in the ConfigureServices method of the Startup class. We can do this by calling the AddAuthentication extension method on the IServiceCollection instance. We then need to configure the authentication scheme by calling the AddScheme method and passing in the scheme name and the authentication options.
public void ConfigureServices(IServiceCollection services)
{
    // Add authentication services
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "BasicAuthentication";
    })
    .AddScheme("BasicAuthentication", null);
}

Step 2: Configure the Authentication Middleware

In the Configure method of the Startup class, we need to add the authentication middleware. We do this by calling the UseAuthentication extension method on the IApplicationBuilder instance.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Add authentication middleware
    app.UseAuthentication();
}

Step 3: Create the BasicAuthenticationHandler

The next step is to create a class that implements the AuthenticationHandler class. This class will be responsible for validating the username and password provided by the client. We can do this by overriding the HandleAuthenticateAsync method.
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.ContainsKey("Authorization"))
            return AuthenticateResult.Fail("Unauthorized");

        var authenticationHeaderValue = Request.Headers["Authorization"];
        var authValues = AuthenticationHeaderValue.Parse(authenticationHeaderValue);

        if (authValues.Scheme != "Basic")
            return AuthenticateResult.Fail("Unauthorized");

        var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authValues.Parameter)).Split(':');

        // Validate the username and password
        // ...

        return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), Scheme.Name));
    }
}

Step 4: Protecting Endpoints

The last step is to protect our endpoints. We can do this by adding the [Authorize] attribute to the controller or action method that we want to protect.
[Authorize]
public class MyController : Controller
{
    // ...
}

Tips for Implementing Basic Authentication in ASP.NET Core Web API

  • Always use HTTPS for basic authentication.
  • Ensure that the username and password are stored securely.
  • Enable two-factor authentication for additional security.
  • Use a unique and complex username and password combination.
  • Limit the number of attempts a user can make to login.

Conclusion

Basic Authentication is a simple and secure way to authenticate clients to access protected endpoints on a web server. In this guide, we have discussed how to implement basic authentication in ASP.NET Core Web API. We have also discussed some tips to ensure that the authentication process is secure.