mirror of
https://github.com/Sea-Haven-Industries/proposal-system.git
synced 2026-09-30 14:43:13 +00:00
42 lines
1.4 KiB
C#
42 lines
1.4 KiB
C#
|
|
using System.Security.Claims;
|
||
|
|
using System.Security.Cryptography;
|
||
|
|
using System.Text;
|
||
|
|
|
||
|
|
namespace ProposalSystem.Api.Middleware;
|
||
|
|
|
||
|
|
public class InternalApiKeyMiddleware
|
||
|
|
{
|
||
|
|
private readonly RequestDelegate _next;
|
||
|
|
private readonly byte[] _apiKeyBytes;
|
||
|
|
|
||
|
|
public InternalApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
|
||
|
|
{
|
||
|
|
_next = next;
|
||
|
|
var key = configuration["INTERNAL_API_KEY"] ?? "";
|
||
|
|
_apiKeyBytes = Encoding.UTF8.GetBytes(key);
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task InvokeAsync(HttpContext context)
|
||
|
|
{
|
||
|
|
if (_apiKeyBytes.Length > 0 &&
|
||
|
|
context.Request.Headers.TryGetValue("X-Internal-Api-Key", out var providedKey) &&
|
||
|
|
!string.IsNullOrEmpty(providedKey.ToString()))
|
||
|
|
{
|
||
|
|
var providedBytes = Encoding.UTF8.GetBytes(providedKey.ToString());
|
||
|
|
if (CryptographicOperations.FixedTimeEquals(providedBytes, _apiKeyBytes))
|
||
|
|
{
|
||
|
|
var claims = new[]
|
||
|
|
{
|
||
|
|
new Claim(ClaimTypes.NameIdentifier, "system"),
|
||
|
|
new Claim(ClaimTypes.Role, "admins"),
|
||
|
|
new Claim("cognito:groups", "admins"),
|
||
|
|
};
|
||
|
|
var identity = new ClaimsIdentity(claims, "InternalApiKey");
|
||
|
|
context.User = new ClaimsPrincipal(identity);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
await _next(context);
|
||
|
|
}
|
||
|
|
}
|