30 lines
1.4 KiB
C#
30 lines
1.4 KiB
C#
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Encodings.Web;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace ApiGateway.Security;
|
|
|
|
public sealed class InternalServiceAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
|
|
ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
|
|
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
|
{
|
|
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
{
|
|
var supplied = Request.Headers["X-Service-Key"].ToString();
|
|
foreach (var service in new[] { "Observation", "Insights", "HealthOverview" })
|
|
{
|
|
var expected = configuration[$"InternalAccess:{service}:Key"]!;
|
|
if (CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(expected)))
|
|
{
|
|
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, "Service"),
|
|
new Claim(ClaimTypes.NameIdentifier, service) }, Scheme.Name);
|
|
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name)));
|
|
}
|
|
}
|
|
return Task.FromResult(AuthenticateResult.Fail("Invalid service credential."));
|
|
}
|
|
}
|