ASP.NET Core: Using API Key Authentication by using Middlewares
In this article, we will implement the ASP.NET Core 8 Authentication using API Key. There are several developers widely use API key authentication to secure API endpoints. To access the API the client must send the valid API Key. This API key is validated on the server once the client sends it in the HTTP request. The client can send the API key in HTTP request in Request Headers, Request Body, and using the Query Parameter. The Figure 1 explains the API Key based authentication implementation
Figure 1: The API Key Authentication
As shown in Figure 1, the execution takes place as stated in the following points, (the following numbering shows numbers displayed in Figure 1)
- The client makes an HTTP request by adding a custom header with an API key in it.
- The request is accepted and it passes through dependencies where the ASP.NET Core DI Registers services for Authentication, Authorization, etc. Make sure that the Authentication and Authorization services are registered in the container to make sure that the API is secured.
- The request is further passed to the HTTP Runtime where Middlewares is configured to process the request.
- Here we can configure the Custom Middleware that will validate the request for Authentication by reading the Custom Header from the incoming HTTP request extracting the API Key from it and using it for the validation.
- If the key is valid the API Logic will be executed and if the Key validation is failed then the unauthorized response will be returned.
- The response is generated based on the Key validation.
- Custom Attribute
- Custom Middleware
- Endpoint filters
- Policy-based Authorization
In this article, we will see the implementation using the Custom Middleware. The advantage of using the Middleware approach is that it allows us to implement and keep the authentication logic separate from the actual application code. This provides a better separation of concerns and reusability. API key authentication using the Middleware-based approach is suitable for larger projects those are having multiple endpoints and complex authentication requirements.
Step 1: Open Visual Studio 2022 and create a new ASP.NET Cor API Project targetted to .NET 7 or .NET 8. In this project, add a new folder and name it Services. In this folder, add a new Interface and name it as IApiAuthKeyValidatorService. This interface will have a method to validate the API Key. The Listing 1 shows the code for this interface.
namespace API_Authentication_ApiKey.Services { public interface IApiAuthKeyValidatorService { void ValidateApiAuthKey(string apiAuthKey, out bool isValid); } }
Listing 1: The IApiAuthKeyValidatorService code
Step 2: Let's modify the appsettings.json file by adding a key/Value pair for the API as shown in Listing 2. Please make sure that in real-world applications, this key must be stored in the environment variables, or for Azure cloud applications, this key must be stored in Azure Key Vault.
"ApiAuthHeader": "X-API-AuthKey", "ApiAuthKey": "d3vnwDLqBCEcNkLY0uIwYg5dzyIAcMtSdwt7DuzdLc="
Listing 2: appsettings.json file that stores the API Key
namespace API_Authentication_ApiKey.Services { public class ApiAuthKeyValidatorService : IApiAuthKeyValidatorService { IConfiguration _configuration; /// <summary> /// Inject the IConfiguration to read ApiAuthKey from appsettings.json /// </summary> /// <param name="configuration"></param> public ApiAuthKeyValidatorService(IConfiguration configuration) { _configuration = configuration; } void IApiAuthKeyValidatorService.ValidateApiAuthKey(string apiAuthKey, out bool isValid) { isValid = false; // Make apiAuthKey is not Null or EMpty if (string.IsNullOrEmpty(apiAuthKey)) isValid = false; // Read the Key from the appsettings.json string? key = _configuration.GetValue<string>("ApiAuthKey"); // Make sure that if (string.IsNullOrEmpty(key)) isValid = false; if (key.Equals(apiAuthKey)) isValid = true; } } }
..... builder.Services.AddTransient<IApiAuthKeyValidatorService, ApiAuthKeyValidatorService>(); .....
Listing 5: The ApiAuthKeyMiddleware Logic code to perform API Key Authentication