| | 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 | | IOptionsMonitor<ApiKeyAuthenticationSchemeOptions> options, |
| | 11 | | ILoggerFactory logger, |
| | 12 | | UrlEncoder encoder, |
| | 13 | | IApiKeyService apiKeyService, |
| | 14 | | IWebHostEnvironment webHostEnvironment |
| 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 | |
|
| | 21 | | protected override async Task<AuthenticateResult> HandleAuthenticateAsync() |
| 0 | 22 | | { |
| 0 | 23 | | if (!_webHostEnvironment.IsDevelopment()) |
| 0 | 24 | | { |
| 0 | 25 | | var apiKey = Context.Request.Headers["X-API-KEY"]; |
| 0 | 26 | | if (string.IsNullOrWhiteSpace(apiKey) || await _apiKeyService.ValidateApiKeyAsync(apiKey!) == false) |
| 0 | 27 | | { |
| 0 | 28 | | return AuthenticateResult.Fail("X-API-KEY is invalid"); |
| | 29 | | } |
| 0 | 30 | | } |
| | 31 | |
|
| 0 | 32 | | var identity = new ClaimsIdentity([], Scheme.Name); |
| 0 | 33 | | var principal = new ClaimsPrincipal(identity); |
| 0 | 34 | | var ticket = new AuthenticationTicket(principal, Scheme.Name); |
| 0 | 35 | | return AuthenticateResult.Success(ticket); |
| 0 | 36 | | } |
| | 37 | | } |