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
+32 -12
View File
@@ -407,33 +407,53 @@ namespace xIds.DI
) )
{ {
// //
// Adding Requirements ...
services.AddXIdentityResourceConfiguration(configuration); services.AddXIdentityResourceConfiguration(configuration);
// //
// Create Authentication Builder ...
var authBuilder = services.AddAuthentication(); var authBuilder = services.AddAuthentication();
// //
// Add JWT Bearer ... // For Best Support we Have to Add ApiKey Authentication First ...
if (addApiKeyAuthentication)
{
//
authBuilder
.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>(
XAuthenticationScheme.XApiKey.GetStringValue(),
options => { });
}
//
// Add JwtBearer by Smart Schema ForwardDefaultSelector ...
authBuilder.AddJwtBearer(options => authBuilder.AddJwtBearer(options =>
{ {
// //
options.SaveToken = true; options.SaveToken = true;
options.RequireHttpsMetadata = false; options.RequireHttpsMetadata = false;
// options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API;
// //
options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; // Selecting Authentication Schema Based On Header ...
options.ForwardDefaultSelector = context =>
{
//
// if Header Contains X-Api-Key use Scheme XApiKey ...
var apiKeyHeader = XHeader.ApiKey
.GetStringValue()
.ToNormalString();
if (context.Request.Headers.ContainsKey(apiKeyHeader))
{
return XAuthenticationScheme.XApiKey.GetStringValue();
}
//
// If Not, Use Local Api ...
return XAuthentication.IDENTITY_SERVER_LOCAL_API;
};
}) })
.AddLocalApi(); .AddLocalApi();
//
if (addApiKeyAuthentication)
{
//
authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>(
XAuthenticationScheme.XApiKey.GetStringValue(),
options => {}
);
}
} }
/// <summary> /// <summary>
+41 -32
View File
@@ -1,11 +1,12 @@
using System.Linq;
using IdentityModel; using IdentityModel;
using xIds.Interfaces; using xIds.Interfaces;
using xCommons.Constants;
using xCommons.Extensions; using xCommons.Extensions;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Security.Claims; using System.Security.Claims;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using xIdentityService.Constants; using xIdentityService.Constants;
using System.Collections.Generic;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
@@ -41,25 +42,30 @@ namespace xIds.Providers
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{ {
// //
var apiKey = var apiKeyHeader = HeaderName;
!Request.Headers.ContainsKey(HeaderName) if (!Request.Headers.ContainsKey(apiKeyHeader))
? string.Empty
: Request.Headers[HeaderName].ToString();
if (apiKey.IsNullOrEmpty())
{ {
return AuthenticateResult.NoResult(); 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 clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
// //
var validationResult = await applicationProvider.ValidateApiKey( // Validating ApiKey ...
apiKey: apiKey, var validationResult = await applicationProvider
clientIP: clientIP .ValidateApiKey(
); apiKey: apiKey,
var isValid = !validationResult.Errors.HasChild(); clientIP: clientIP
if (!isValid) );
if (validationResult.Errors.HasChild())
{ {
// //
var message = validationResult.Errors.ToListString('\n'); var message = validationResult.Errors.ToListString('\n');
@@ -67,32 +73,35 @@ namespace xIds.Providers
} }
// //
var claims = new[] // Creating Claims ...
{ var claims = new List<Claim> {
new Claim(ClaimTypes.Name, validationResult.OwnerId), //
new Claim("application_id", validationResult.ApplicationId.ToString()), // Owner Identifier of API Key ...
new Claim("auth_type", "apikey"), new(ClaimTypes.Name, validationResult.OwnerId),
new Claim(JwtClaimTypes.Scope, "apikey"), new(JwtClaimTypes.Subject, validationResult.OwnerId),
//
// Application Id ...
new(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()),
//
// Authentication Type ...
new(XCustomClaims.AuthType, "apikey"),
}; };
// //
var scopeClaims = validationResult.Scopes // Add Scopes ...
.Select(s => new Claim(JwtClaimTypes.Scope, s)); if (validationResult.Scopes != null)
{
// foreach (var scope in validationResult.Scopes)
var identity = new ClaimsIdentity( {
claims.Union(scopeClaims), claims.Add(new Claim(JwtClaimTypes.Scope, scope));
AuthenticationScheme }
); }
// //
// Create Principal and Ticket ...
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity); var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
//
var ticket = new AuthenticationTicket(
principal,
AuthenticationScheme
);
// //
return AuthenticateResult.Success(ticket); return AuthenticateResult.Success(ticket);