Skip to main content

Command Palette

Search for a command to run...

Minimal API-Key Solution

Published
1 min read
Minimal API-Key Solution
S
Sascha Manns is a programmer and author in Germany.

Problem
I searched for a Solution for a API-Key whith minimal Expense.

Solution
ApiKeyMiddleware:

```public class ApiKeyMiddleware
{
private readonly RequestDelegate *next;
private const string APIKEYNAME = "ApiKey";

public ApiKeyMiddleware(RequestDelegate next)
{
*next = next;
}

public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API-Key not found.");
return;
}
}

var appSettings = context.RequestServices.GetRequiredService();
var apiKey = appSettings.GetValaue(APIKEYNAME);
if (!apiKey.Equals(extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Client not authorized.");
return;
}
await _next(context)

}```

Then in a Project.cs:
```app.UseMiddleware();```

3 views