From 8bbd047e93627427bad79242d93d94b57f96e8c5 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Wed, 14 Oct 2026 17:33:24 +0330 Subject: [PATCH] last ... --- Controllers/Account/AccountController+Test.cs | 8 +- .../ApplicationsController+Custom.cs | 10 +- DI/XDIHelperExtension.cs | 45 ------ ...ionFilter.cs => XApiKeyAccessAttribute.cs} | 85 ++++------ Providers/XApiKeyAuthenticationHandler.cs | 145 ------------------ .../XApplicationProvider+Custom.cs | 10 +- 6 files changed, 49 insertions(+), 254 deletions(-) rename Providers/{XApiKeyAuthorizationFilter.cs => XApiKeyAccessAttribute.cs} (67%) delete mode 100644 Providers/XApiKeyAuthenticationHandler.cs diff --git a/Controllers/Account/AccountController+Test.cs b/Controllers/Account/AccountController+Test.cs index 029283c..4bdbe09 100644 --- a/Controllers/Account/AccountController+Test.cs +++ b/Controllers/Account/AccountController+Test.cs @@ -1,7 +1,9 @@ using System.Linq; +using xIds.Providers; using xIdentityHelper; using xCommons.Attributes; using Microsoft.AspNetCore.Mvc; +using xIdentityModels.Constants; using Microsoft.AspNetCore.Authorization; using static IdentityServer4.IdentityServerConstants; @@ -157,10 +159,12 @@ namespace xIds.Controllers return Ok(result); } + [AllowAnonymous] [RequireXPowered] [HttpGet("Test/HiApiKeyAccess")] - // [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.ApiKeyAccess)] + [Authorize(LocalApi.PolicyName)] + [XApiKeyAccess(scopes: [XApiKeyScope.Read])] + // [Authorize(Policy = XPolicies.ApiKeyAccess)] public ActionResult HiApiKeyAccess() { // diff --git a/Controllers/Applications/ApplicationsController+Custom.cs b/Controllers/Applications/ApplicationsController+Custom.cs index b02fa7e..a4810aa 100644 --- a/Controllers/Applications/ApplicationsController+Custom.cs +++ b/Controllers/Applications/ApplicationsController+Custom.cs @@ -256,20 +256,20 @@ namespace xIds.Controllers // Normalize ... if ( request.IsNullOrDefault() || - request.NewExpiration.IsNull() || - !request.NewExpiration.HasValue + request.NewExpirationMinutes.IsNull() || + !request.NewExpirationMinutes.HasValue ) { // - var timeSpan = TimeSpan.FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes); request = new XRotateApiKeyRequest { - NewExpiration = timeSpan + NewExpirationMinutes = apiKeyConfiguration.DefaultExpirationMinutes }; } // var userInfo = await GetUserInfo(); + var timeSpan = TimeSpan.FromMinutes(request.NewExpirationMinutes.Value); // // Retrieve Application for Validating ... @@ -288,7 +288,7 @@ namespace xIds.Controllers var result = await provider.RotateApiKey( apiKeyId: apiKeyId, userInfo: userInfo, - newExpiration: request.NewExpiration, + newExpiration: timeSpan, cancellationToken: cancellationToken ); diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index 7845ad2..69d934f 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -25,9 +25,7 @@ using xIdentityModels.Configurations; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Configuration; -using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.DependencyInjection; -using xIdentityService.Constants; namespace xIds.DI { @@ -412,49 +410,6 @@ namespace xIds.DI // Create Authentication Builder ... 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( - // XAuthenticationScheme.XApiKey.GetStringValue(), - // options => { }); - // // Add JwtBearer by Smart Schema ForwardDefaultSelector ... authBuilder.AddJwtBearer(options => diff --git a/Providers/XApiKeyAuthorizationFilter.cs b/Providers/XApiKeyAccessAttribute.cs similarity index 67% rename from Providers/XApiKeyAuthorizationFilter.cs rename to Providers/XApiKeyAccessAttribute.cs index 1812d93..aebfca1 100644 --- a/Providers/XApiKeyAuthorizationFilter.cs +++ b/Providers/XApiKeyAccessAttribute.cs @@ -1,12 +1,11 @@ using System; -using System.Linq; -using xIds.Helpers; using IdentityModel; using xIds.Interfaces; -using xIdentityHelper; using xCommons.Constants; using xCommons.Extensions; +using xExceptions.Constants; using System.Security.Claims; +using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using xIdentityModels.Constants; @@ -14,7 +13,6 @@ using xIdentityService.Constants; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Authorization; -using System.Threading.Tasks; namespace xIds.Providers { @@ -23,27 +21,27 @@ namespace xIds.Providers AllowMultiple = false, Inherited = true )] - public class XApiKeyAuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter + public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter { - // /// - // /// Optional required scope for this endpoint. - // /// Example: [XApiKeyAuthorizationFilter(RequiredScope = "read")] - // /// - // public string RequiredScope { get; set; } + /// + /// Optional allowed scopes. If empty, no scope enforcement. + /// + public XApiKeyScope[] Scopes { get; set; } - // /// - // /// If false, a missing header will only result in NoResult (anonymous) - // /// instead of a 401. Default is true (must provide a key). - // /// - // public bool ApiKeyRequired { get; set; } = true; + public XApiKeyAccessAttribute( + XApiKeyScope[] scopes = null + ) + { + // + if (!scopes.HasChild()) + { + scopes = [XApiKeyScope.Manage]; + } - // /// - // /// Optional allowed scopes. If empty, no scope enforcement. - // /// - // public string[] AllowedScopes { get; set; } + // + Scopes = scopes; + } - public XApiKeyAuthorizationFilter() { } - /// /// Authorization Filtering ... /// @@ -63,6 +61,8 @@ namespace xIds.Providers // // Access HttpContext ... var http = context.HttpContext; + var error = XException.NotAuthorized.ToXError(); + var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue(); // try @@ -71,32 +71,6 @@ namespace xIds.Providers // Obtain the endpoint currently being executed 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(); - 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 ... var applicationProvider = http.RequestServices @@ -105,18 +79,19 @@ namespace xIds.Providers 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; } // // Checking Header ... var apiKeyHeader = XHeader.ApiKey.GetStringValue(); - var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue(); 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; } @@ -126,7 +101,8 @@ namespace xIds.Providers if (apiKey.IsNullOrEmpty()) { // - context.Result = new UnauthorizedObjectResult("ApiKey not Provided ..."); + error.Message = "ApiKey not Provided ..."; + context.Result = new UnauthorizedObjectResult(error.ToJSON()); return; } @@ -145,7 +121,8 @@ namespace xIds.Providers { // var message = validationResult.Errors.ToListString('\n'); - context.Result = new UnauthorizedObjectResult(message); + error.Message = message; + context.Result = new UnauthorizedObjectResult(error.ToJSON()); return; } @@ -185,7 +162,9 @@ namespace xIds.Providers } catch { - context.Result = new UnauthorizedObjectResult("ApiKey authorization failed ..."); + // + error.Message = "ApiKey authorization failed ..."; + context.Result = new UnauthorizedObjectResult(error.ToJSON()); } } } diff --git a/Providers/XApiKeyAuthenticationHandler.cs b/Providers/XApiKeyAuthenticationHandler.cs deleted file mode 100644 index 26aa9ac..0000000 --- a/Providers/XApiKeyAuthenticationHandler.cs +++ /dev/null @@ -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 -{ - /// - /// an Authentication Handler for ApiKey's based App's ... - /// - public class XApiKeyAuthenticationHandler : AuthenticationHandler - { - 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 options - ) : base(options, logger, encoder, clock) - { - this.applicationProvider = applicationProvider; - } - - /// - /// Handle Authentication ... - /// - /// - protected override async Task 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(); - 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 { - // - // 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); - } - } -} \ No newline at end of file diff --git a/Providers/XApplicationProvider/XApplicationProvider+Custom.cs b/Providers/XApplicationProvider/XApplicationProvider+Custom.cs index 735afb5..4a0e7a6 100644 --- a/Providers/XApplicationProvider/XApplicationProvider+Custom.cs +++ b/Providers/XApplicationProvider/XApplicationProvider+Custom.cs @@ -429,10 +429,12 @@ namespace xIds.Providers // // Here we Have to Parse Allowed Ips and Scopes ... - var allowedIps = (keyModel.AllowedIPs ?? string.Empty) - .ParseListString(); - var allowedScopes = (keyModel.AllowedScopes ?? string.Empty) - .FromJSON>(); + var allowedIps = keyModel.AllowedIPs.IsNullOrEmpty() + ? [] + : keyModel.AllowedIPs.ParseListString(); + var allowedScopes = keyModel.AllowedScopes.IsNullOrEmpty() + ? [] + : keyModel.AllowedScopes.FromJSON>(); result.Scopes = [.. allowedScopes]; //