-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApiKeyMiddleware.cs
More file actions
43 lines (37 loc) · 1.22 KB
/
Copy pathApiKeyMiddleware.cs
File metadata and controls
43 lines (37 loc) · 1.22 KB
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
41
42
43
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using System.Threading.Tasks;
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IUserService userService)
{
var endpoint = context.GetEndpoint();
if (endpoint != null)
{
var descriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
if (descriptor != null && descriptor.ControllerName == "Auth" && descriptor.ActionName == "Login")
{
await _next(context);
return;
}
}
if (!context.Request.Headers.TryGetValue("ApiKey", out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key is required.");
return;
}
if (!userService.ValidateApiKey(extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
return;
}
await _next(context);
}
}