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 options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration) : AuthenticationHandler(options, logger, encoder) { protected override Task 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.")); } }