Files
xIdentityService/Handlers/XApiKeyAuthenticationHandler.cs
2026-11-20 20:23:01 +03:30

66 lines
2.2 KiB
C#

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<AuthenticationSchemeOptions>
{
private readonly IXIdentityProvider identityProvider;
public XApiKeyAuthenticationHandler(
UrlEncoder encoder,
ILoggerFactory logger,
ISystemClock systemClock,
IXIdentityProvider identityProvider,
IOptionsMonitor<AuthenticationSchemeOptions> options
) : base(options, logger, encoder, systemClock)
{
this.identityProvider = identityProvider;
}
protected override async Task<AuthenticateResult> 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)));
}
}
}