|  |  | 1 |  | using System.Security.Claims; | 
|  |  | 2 |  | using System.Text.Encodings.Web; | 
|  |  | 3 |  | using LGDXRobotCloud.API.Services.Administration; | 
|  |  | 4 |  | using Microsoft.AspNetCore.Authentication; | 
|  |  | 5 |  | using Microsoft.Extensions.Options; | 
|  |  | 6 |  |  | 
|  |  | 7 |  | namespace LGDXRobotCloud.API.Authentication; | 
|  |  | 8 |  |  | 
|  |  | 9 |  | public class ApiKeyAuthenticationSchemeHandler( | 
|  |  | 10 |  |     IApiKeyService apiKeyService, | 
|  |  | 11 |  |     ILoggerFactory logger, | 
|  |  | 12 |  |     IOptionsMonitor<ApiKeyAuthenticationSchemeOptions> options, | 
|  |  | 13 |  |     IWebHostEnvironment webHostEnvironment, | 
|  |  | 14 |  |     UrlEncoder encoder | 
|  | 0 | 15 |  |   ) : AuthenticationHandler<ApiKeyAuthenticationSchemeOptions>(options, logger, encoder) | 
|  |  | 16 |  | { | 
|  | 0 | 17 |  |   private readonly IApiKeyService _apiKeyService = apiKeyService ?? throw new ArgumentNullException(nameof(apiKeyService | 
|  | 0 | 18 |  |   private readonly IWebHostEnvironment _webHostEnvironment = webHostEnvironment ?? throw new ArgumentNullException(nameo | 
|  |  | 19 |  |  | 
|  |  | 20 |  |   protected override async Task<AuthenticateResult> HandleAuthenticateAsync() | 
|  | 0 | 21 |  |   { | 
|  | 0 | 22 |  |     string? apiKey = Context.Request.Headers["X-API-KEY"]; | 
|  | 0 | 23 |  |     var apiKeyId = await _apiKeyService.ValidateApiKeyAsync(apiKey); | 
|  | 0 | 24 |  |     if (!_webHostEnvironment.IsDevelopment() && apiKeyId == null) | 
|  | 0 | 25 |  |     { | 
|  | 0 | 26 |  |       return AuthenticateResult.Fail("X-API-KEY is invalid"); | 
|  |  | 27 |  |     } | 
|  |  | 28 |  |  | 
|  | 0 | 29 |  |     Context.Items["ApiKeyId"] = apiKeyId; | 
|  | 0 | 30 |  |     var identity = new ClaimsIdentity([], Scheme.Name); | 
|  | 0 | 31 |  |     var principal = new ClaimsPrincipal(identity); | 
|  | 0 | 32 |  |     var ticket = new AuthenticationTicket(principal, Scheme.Name); | 
|  | 0 | 33 |  |     return AuthenticateResult.Success(ticket); | 
|  | 0 | 34 |  |   } | 
|  |  | 35 |  | } |