Basic authentication in ASP.NET Core

Basic authentication is used in a HTTP request by adding a Base64 encoded username and password to the Authorization header.

It is used in OAuth as part of the client credentials flow for requesting an access token in the form of a Bearer token.

What's included?

The code sample will give you the functionality to add Basic authentication into an ASP.NET Core Web API.

C# coding challenges

C# coding challenges

Our online code editor allows you to compile the answer.

This includes the authorize attribute, client identity and the authentication handler. In-addition, a controller has been set up to use Basic authentication along with configuration in Swagger. This means that it can tested when running the web app.

Watch our video to see what files are included, how we implemented the functionality and how we tested it.

In addition, you can read more about Basic authentication so you get a better understanding of how it can be used as part of the OAuth Client Credentials grant type.

This code example has been updated to .NET 8.

The order process

When you purchase the code example, you'll be given a ZIP file that contains all the code files that you can download and extract onto your machine.

Simply add your e-mail address to the form below, agree to the terms and conditions, and you'll be redirected to our payment provider to take payment.

On successful payment, our payment provider will redirect you to a page where you can download the ZIP file. A link to download the ZIP file will also be emailed to you.

Software

This is the software that will need to be installed onto your machine.

Open the project in Visual Studio

Open up RoundTheCode.BasicAuthentication.sln in Visual Studio. The start up project should be set to RoundTheCode.BasicAuthentication.WebApi which is the ASP.NET Core Web API.

Start the application, and your browser should open up to https://localhost:9902 with the Swagger documentation.

To add a username and password to an API request, click on the padlock icon.

How to use Basic authentication in Swagger

How to use Basic authentication in Swagger

Add the username and password as roundthecode.

Add username and password for Basic authentication in Swagger

Add username and password for Basic authentication in Swagger

Executing the request, the API request should return a 200 response. Everything else should return a 401 response.