This commit is contained in:
2026-10-14 17:33:24 +03:30
parent 4d2193c3b9
commit 8bbd047e93
6 changed files with 49 additions and 254 deletions
@@ -1,7 +1,9 @@
using System.Linq; using System.Linq;
using xIds.Providers;
using xIdentityHelper; using xIdentityHelper;
using xCommons.Attributes; using xCommons.Attributes;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using xIdentityModels.Constants;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using static IdentityServer4.IdentityServerConstants; using static IdentityServer4.IdentityServerConstants;
@@ -157,10 +159,12 @@ namespace xIds.Controllers
return Ok(result); return Ok(result);
} }
[AllowAnonymous]
[RequireXPowered] [RequireXPowered]
[HttpGet("Test/HiApiKeyAccess")] [HttpGet("Test/HiApiKeyAccess")]
// [Authorize(LocalApi.PolicyName)] [Authorize(LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.ApiKeyAccess)] [XApiKeyAccess(scopes: [XApiKeyScope.Read])]
// [Authorize(Policy = XPolicies.ApiKeyAccess)]
public ActionResult<string> HiApiKeyAccess() public ActionResult<string> HiApiKeyAccess()
{ {
// //
@@ -256,20 +256,20 @@ namespace xIds.Controllers
// Normalize ... // Normalize ...
if ( if (
request.IsNullOrDefault() || request.IsNullOrDefault() ||
request.NewExpiration.IsNull() || request.NewExpirationMinutes.IsNull() ||
!request.NewExpiration.HasValue !request.NewExpirationMinutes.HasValue
) )
{ {
// //
var timeSpan = TimeSpan.FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes);
request = new XRotateApiKeyRequest request = new XRotateApiKeyRequest
{ {
NewExpiration = timeSpan NewExpirationMinutes = apiKeyConfiguration.DefaultExpirationMinutes
}; };
} }
// //
var userInfo = await GetUserInfo(); var userInfo = await GetUserInfo();
var timeSpan = TimeSpan.FromMinutes(request.NewExpirationMinutes.Value);
// //
// Retrieve Application for Validating ... // Retrieve Application for Validating ...
@@ -288,7 +288,7 @@ namespace xIds.Controllers
var result = await provider.RotateApiKey( var result = await provider.RotateApiKey(
apiKeyId: apiKeyId, apiKeyId: apiKeyId,
userInfo: userInfo, userInfo: userInfo,
newExpiration: request.NewExpiration, newExpiration: timeSpan,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
-45
View File
@@ -25,9 +25,7 @@ using xIdentityModels.Configurations;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using xIdentityService.Constants;
namespace xIds.DI namespace xIds.DI
{ {
@@ -412,49 +410,6 @@ namespace xIds.DI
// Create Authentication Builder ... // Create Authentication Builder ...
var authBuilder = services.AddAuthentication(); var authBuilder = services.AddAuthentication();
//
// Create Authentication Builder ...
// var authBuilder = services.AddAuthentication(options =>
// {
// //
// // Setting Default Authentication Schema ...
// // For Handling Smart Schema Forwarder ...
// options.DefaultScheme = XAuthentication.SMART_SCHEME;
// options.DefaultChallengeScheme = XAuthentication.SMART_SCHEME;
// options.DefaultAuthenticateScheme = XAuthentication.SMART_SCHEME;
// })
// .AddPolicyScheme(
// displayName: XAuthentication.SMART_SCHEME,
// authenticationScheme: XAuthentication.SMART_SCHEME,
// configureOptions: options =>
// {
// //
// // Configure Forward Default Selector ...
// options.ForwardDefaultSelector = context =>
// {
// //
// // Retrieve XApiKey Header Key ...
// var apiKeyHeader = XHeader.ApiKey.GetStringValue();
// //
// // If Header Contains Key ...
// if (context.Request.Headers.ContainsKey(apiKeyHeader))
// {
// return XAuthenticationScheme.XApiKey.GetStringValue();
// }
// //
// // If not ...
// return XAuthentication.IDENTITY_SERVER_LOCAL_API;
// };
// }
// );
//
// authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>(
// XAuthenticationScheme.XApiKey.GetStringValue(),
// options => { });
// //
// Add JwtBearer by Smart Schema ForwardDefaultSelector ... // Add JwtBearer by Smart Schema ForwardDefaultSelector ...
authBuilder.AddJwtBearer(options => authBuilder.AddJwtBearer(options =>
@@ -1,12 +1,11 @@
using System; using System;
using System.Linq;
using xIds.Helpers;
using IdentityModel; using IdentityModel;
using xIds.Interfaces; using xIds.Interfaces;
using xIdentityHelper;
using xCommons.Constants; using xCommons.Constants;
using xCommons.Extensions; using xCommons.Extensions;
using xExceptions.Constants;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using xIdentityModels.Constants; using xIdentityModels.Constants;
@@ -14,7 +13,6 @@ using xIdentityService.Constants;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;
namespace xIds.Providers namespace xIds.Providers
{ {
@@ -23,26 +21,26 @@ namespace xIds.Providers
AllowMultiple = false, AllowMultiple = false,
Inherited = true Inherited = true
)] )]
public class XApiKeyAuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter
{ {
// /// <summary> /// <summary>
// /// Optional required scope for this endpoint. /// Optional allowed scopes. If empty, no scope enforcement.
// /// Example: [XApiKeyAuthorizationFilter(RequiredScope = "read")] /// </summary>
// /// </summary> public XApiKeyScope[] Scopes { get; set; }
// public string RequiredScope { get; set; }
// /// <summary> public XApiKeyAccessAttribute(
// /// If false, a missing header will only result in NoResult (anonymous) XApiKeyScope[] scopes = null
// /// instead of a 401. Default is true (must provide a key). )
// /// </summary> {
// public bool ApiKeyRequired { get; set; } = true; //
if (!scopes.HasChild())
{
scopes = [XApiKeyScope.Manage];
}
// /// <summary> //
// /// Optional allowed scopes. If empty, no scope enforcement. Scopes = scopes;
// /// </summary> }
// public string[] AllowedScopes { get; set; }
public XApiKeyAuthorizationFilter() { }
/// <summary> /// <summary>
/// Authorization Filtering ... /// Authorization Filtering ...
@@ -63,6 +61,8 @@ namespace xIds.Providers
// //
// Access HttpContext ... // Access HttpContext ...
var http = context.HttpContext; var http = context.HttpContext;
var error = XException.NotAuthorized.ToXError();
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
// //
try try
@@ -71,32 +71,6 @@ namespace xIds.Providers
// Obtain the endpoint currently being executed // Obtain the endpoint currently being executed
var endpoint = http.GetEndpoint(); var endpoint = http.GetEndpoint();
//
// Retrieve all AuthorizeAttribute metadata from the endpoint
var hasApiKeyScheme = false;
var apiKeyScopes = XApiKeyHelper.GetXApiKeyScopes();
var apiKeyPolicies = XApiKeyHelper.GetXApiKeyPolicies();
var authorizeAttributes = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>();
if (
apiKeyPolicies.HasChild() &&
authorizeAttributes.HasChild()
)
{
//
// Retrieve a List of ApiKey Policies ...
hasApiKeyScheme = authorizeAttributes.Any(attr =>
apiKeyPolicies.Any(asc => asc.ToNormalString() == attr.Policy.ToNormalString())
);
}
//
// if there is not any Policies for ApiKey Authentication
// or Authorization, pass no Result ...
if (!hasApiKeyScheme)
{
return;
}
// //
// Retrieve the application provider from DI ... // Retrieve the application provider from DI ...
var applicationProvider = http.RequestServices var applicationProvider = http.RequestServices
@@ -105,18 +79,19 @@ namespace xIds.Providers
if (applicationProvider.IsNull()) if (applicationProvider.IsNull())
{ {
// //
context.Result = new UnauthorizedObjectResult("Provider Service Not Registered ..."); error.Message = "Api Key Service not Registered ...";
context.Result = new UnauthorizedObjectResult(error.ToJSON());
return; return;
} }
// //
// Checking Header ... // Checking Header ...
var apiKeyHeader = XHeader.ApiKey.GetStringValue(); var apiKeyHeader = XHeader.ApiKey.GetStringValue();
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
if (!http.Request.Headers.ContainsKey(apiKeyHeader)) if (!http.Request.Headers.ContainsKey(apiKeyHeader))
{ {
// //
context.Result = new UnauthorizedObjectResult("ApiKey not Exists ..."); error.Message = "ApiKey not Exists ...";
context.Result = new UnauthorizedObjectResult(error.ToJSON());
return; return;
} }
@@ -126,7 +101,8 @@ namespace xIds.Providers
if (apiKey.IsNullOrEmpty()) if (apiKey.IsNullOrEmpty())
{ {
// //
context.Result = new UnauthorizedObjectResult("ApiKey not Provided ..."); error.Message = "ApiKey not Provided ...";
context.Result = new UnauthorizedObjectResult(error.ToJSON());
return; return;
} }
@@ -145,7 +121,8 @@ namespace xIds.Providers
{ {
// //
var message = validationResult.Errors.ToListString('\n'); var message = validationResult.Errors.ToListString('\n');
context.Result = new UnauthorizedObjectResult(message); error.Message = message;
context.Result = new UnauthorizedObjectResult(error.ToJSON());
return; return;
} }
@@ -185,7 +162,9 @@ namespace xIds.Providers
} }
catch catch
{ {
context.Result = new UnauthorizedObjectResult("ApiKey authorization failed ..."); //
error.Message = "ApiKey authorization failed ...";
context.Result = new UnauthorizedObjectResult(error.ToJSON());
} }
} }
} }
-145
View File
@@ -1,145 +0,0 @@
using System.Linq;
using xIds.Helpers;
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 Microsoft.AspNetCore.Http;
using xIdentityService.Constants;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
namespace xIds.Providers
{
/// <summary>
/// an Authentication Handler for ApiKey's based App's ...
/// </summary>
public class XApiKeyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IXApplicationProvider applicationProvider;
//
public string HeaderName { get; } = XHeader.ApiKey.GetStringValue();
public string AuthenticationScheme { get; } = XAuthenticationScheme.XApiKey.GetStringValue();
public XApiKeyAuthenticationHandler(
UrlEncoder encoder,
ISystemClock clock,
ILoggerFactory logger,
IXApplicationProvider applicationProvider,
IOptionsMonitor<AuthenticationSchemeOptions> options
) : base(options, logger, encoder, clock)
{
this.applicationProvider = applicationProvider;
}
/// <summary>
/// Handle Authentication ...
/// </summary>
/// <returns></returns>
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
//
// Obtain the endpoint currently being executed
var endpoint = Context.GetEndpoint();
//
// Retrieve all AuthorizeAttribute metadata from the endpoint
var hasApiKeyScheme = false;
var apiKeyScopes = XApiKeyHelper.GetXApiKeyScopes();
var apiKeyPolicies = XApiKeyHelper.GetXApiKeyPolicies();
var authorizeAttributes = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>();
if (
apiKeyPolicies.HasChild() &&
authorizeAttributes.HasChild()
)
{
//
// Retrieve a List of ApiKey Policies ...
hasApiKeyScheme = authorizeAttributes.Any(attr =>
apiKeyPolicies.Any(asc => asc.ToNormalString() == attr.Policy.ToNormalString()) ||
attr.AuthenticationSchemes.ToNormalString() == XAuthenticationScheme.XApiKey.GetStringValue().ToNormalString()
);
}
//
// if there is not any Policies for ApiKey Authentication
// or Authorization, pass no Result ...
if (!hasApiKeyScheme)
{
return AuthenticateResult.NoResult();
}
//
var apiKeyHeader = HeaderName;
if (!Request.Headers.ContainsKey(apiKeyHeader))
{
return AuthenticateResult.Fail("ApiKey not Exists ...");
}
//
var apiKey = Request.Headers[apiKeyHeader].ToString();
if (apiKey.IsNullOrEmpty())
{
return AuthenticateResult.Fail("ApiKey not Provided ...");
}
// Extract Client IP ...
var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
//
// Validating ApiKey ...
var validationResult = await applicationProvider
.ValidateApiKey(
apiKey: apiKey,
clientIP: clientIP
);
if (validationResult.Errors.HasChild())
{
//
var message = validationResult.Errors.ToListString('\n');
return AuthenticateResult.Fail(message);
}
//
// 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"),
};
//
// Add Scopes ...
if (validationResult.Scopes != null)
{
foreach (var scope in validationResult.Scopes)
{
claims.Add(new Claim(JwtClaimTypes.Scope, scope));
}
}
//
// 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);
}
}
}
@@ -429,10 +429,12 @@ namespace xIds.Providers
// //
// Here we Have to Parse Allowed Ips and Scopes ... // Here we Have to Parse Allowed Ips and Scopes ...
var allowedIps = (keyModel.AllowedIPs ?? string.Empty) var allowedIps = keyModel.AllowedIPs.IsNullOrEmpty()
.ParseListString<string>(); ? []
var allowedScopes = (keyModel.AllowedScopes ?? string.Empty) : keyModel.AllowedIPs.ParseListString<string>();
.FromJSON<IEnumerable<string>>(); var allowedScopes = keyModel.AllowedScopes.IsNullOrEmpty()
? []
: keyModel.AllowedScopes.FromJSON<IEnumerable<string>>();
result.Scopes = [.. allowedScopes]; result.Scopes = [.. allowedScopes];
// //