-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPIKeyCheckMiddleware.cs
40 lines (33 loc) · 1.1 KB
/
APIKeyCheckMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using Microsoft.Extensions.Primitives;
namespace SecretDeliveryApp;
internal class APIKeyCheckMiddleware
{
public const string API_KEY_HEADER_NAME = "X-API-KEY";
private readonly RequestDelegate _next;
public APIKeyCheckMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.Request.Headers.TryGetValue(API_KEY_HEADER_NAME, out StringValues value))
{
var apiKey = value;
var validApiKey = Environment.GetEnvironmentVariable(API_KEY_HEADER_NAME);
if (validApiKey != null && apiKey == validApiKey)
{
await _next(httpContext);
return;
}
}
httpContext.Response.StatusCode = 403;
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class APIKeyCheckMiddlewareExtensions
{
public static IApplicationBuilder UseAPIKeyCheckMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<APIKeyCheckMiddleware>();
}
}