using System.Linq; using xCommons.Extensions; using System.Security.Claims; using xIdentityModels.Models; using System.Threading.Tasks; using System.Text.Encodings.Web; using System.Collections.Generic; using xIdentityService.Constants; using xIdentityModels.Extensions; using xIdentityService.Interfaces; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.AspNetCore.Authentication; namespace xIdentityService.Handlers { public class XApiKeyAuthenticationHandler : AuthenticationHandler { private readonly IXIdentityProvider identityProvider; public XApiKeyAuthenticationHandler( UrlEncoder encoder, ILoggerFactory logger, ISystemClock systemClock, IXIdentityProvider identityProvider, IOptionsMonitor options ) : base(options, logger, encoder, systemClock) { this.identityProvider = identityProvider; } protected override async Task HandleAuthenticateAsync() { // var header = XHeader.ApiKey.GetStringValue(); if (!Request.Headers.TryGetValue(header, out var raw) || raw.ToString().IsNullOrEmpty()) { return await Task.FromResult(AuthenticateResult.NoResult()); } // var response = await identityProvider.ValidateApiKey(new XApiKeyValidationRequest { ApiKey = raw.ToString(), ClientIP = Context.Connection.RemoteIpAddress?.ToString() }, Context.RequestAborted); // if (response.Errors.HasChild()) { // return await Task.FromResult( AuthenticateResult.Fail(string.Join(",", response.Errors))); } // var identity = new ClaimsIdentity(response.ToXClaims(), Scheme.Name); var principal = new ClaimsPrincipal(identity); // return await Task.FromResult(AuthenticateResult.Success( new AuthenticationTicket(principal, Scheme.Name))); } } }