This commit is contained in:
2026-10-10 16:23:41 +03:30
parent 5085fc54a4
commit bfd60e9bb3
2 changed files with 77 additions and 48 deletions
+43 -34
View File
@@ -1,11 +1,12 @@
using System.Linq;
using IdentityModel;
using xIds.Interfaces;
using xCommons.Constants;
using xCommons.Extensions;
using System.Threading.Tasks;
using System.Security.Claims;
using System.Text.Encodings.Web;
using xIdentityService.Constants;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication;
@@ -41,25 +42,30 @@ namespace xIds.Providers
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
//
var apiKey =
!Request.Headers.ContainsKey(HeaderName)
? string.Empty
: Request.Headers[HeaderName].ToString();
var apiKeyHeader = HeaderName;
if (!Request.Headers.ContainsKey(apiKeyHeader))
{
return AuthenticateResult.NoResult();
}
//
var apiKey = Request.Headers[apiKeyHeader].ToString();
if (apiKey.IsNullOrEmpty())
{
return AuthenticateResult.NoResult();
}
//
// Extract Client IP ...
var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
//
var validationResult = await applicationProvider.ValidateApiKey(
apiKey: apiKey,
clientIP: clientIP
);
var isValid = !validationResult.Errors.HasChild();
if (!isValid)
// Validating ApiKey ...
var validationResult = await applicationProvider
.ValidateApiKey(
apiKey: apiKey,
clientIP: clientIP
);
if (validationResult.Errors.HasChild())
{
//
var message = validationResult.Errors.ToListString('\n');
@@ -67,32 +73,35 @@ namespace xIds.Providers
}
//
var claims = new[]
{
new Claim(ClaimTypes.Name, validationResult.OwnerId),
new Claim("application_id", validationResult.ApplicationId.ToString()),
new Claim("auth_type", "apikey"),
new Claim(JwtClaimTypes.Scope, "apikey"),
// Creating Claims ...
var claims = new List<Claim> {
//
// Owner Identifier of API Key ...
new(ClaimTypes.Name, validationResult.OwnerId),
new(JwtClaimTypes.Subject, validationResult.OwnerId),
//
// Application Id ...
new(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()),
//
// Authentication Type ...
new(XCustomClaims.AuthType, "apikey"),
};
//
var scopeClaims = validationResult.Scopes
.Select(s => new Claim(JwtClaimTypes.Scope, s));
//
var identity = new ClaimsIdentity(
claims.Union(scopeClaims),
AuthenticationScheme
);
//
var principal = new ClaimsPrincipal(identity);
// Add Scopes ...
if (validationResult.Scopes != null)
{
foreach (var scope in validationResult.Scopes)
{
claims.Add(new Claim(JwtClaimTypes.Scope, scope));
}
}
//
var ticket = new AuthenticationTicket(
principal,
AuthenticationScheme
);
// Create Principal and Ticket ...
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
//
return AuthenticateResult.Success(ticket);