API Key in .NET WebAPI Project
.NET
Create a webapi project, e.g.:
dotnet new webapi -o MyMicroservice
Add a middleware class:
public class ApiKeyMiddleware
{
private readonly string _apiKeyName;
private readonly string _apiKeyValue;
private readonly RequestDelegate _next;
public ApiKeyMiddleware(RequestDelegate next, string apiKeyName, string apiKeyValue)
{
= next;
_next = apiKeyName;
_apiKeyName = apiKeyValue;
_apiKeyValue }
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(_apiKeyName, out var extractedApiKey))
{
.Response.StatusCode = 401;
context.Response.WriteAsync("API Key was not provided.");
await contextreturn;
}
if (!_apiKeyValue.Equals(extractedApiKey))
{
.Response.StatusCode = 403;
context.Response.WriteAsync("Unauthorized client.");
await contextreturn;
}
_next(context);
await }
}
Handle the API key check in Program.cs with the following code. Place this before the app.MapControllers()
call:
string? apiKeyName = "My-Api-Key-Name";
string? apiKeyValue = "85a80751-cc34-4a6e-9ad9-4d9c9bea403c"; // Do NOT store your actual key value inline!
// Retrieve it from a protected
// location, e.g., an Azure key vault.
// Validate the request:
.UseMiddleware<ApiKeyMiddleware>(apiKeyName, apiKeyValue); app
Calls to the API look like this:
GET https://your_webservice_url/some_endpoint
Accept: application/json
My-Api-Key-Name: 85a80751-cc34-4a6e-9ad9-4d9c9bea403c