From 002882300d61a5258dcc2c383bb1dc617924ceda Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Fri, 20 Nov 2026 20:23:01 +0330 Subject: [PATCH] last ... --- Attributes/XApiKeyAccessAttribute.cs | 38 +-- Authorization/XApiKeyRoleRequirement.cs | 41 +++ Authorization/XApiKeyScopeRequirement .cs | 54 ++++ Handlers/XApiKeyAuthenticationHandler.cs | 66 +++++ Interfaces/IXAuthorizationProvider.cs | 222 +++++++------- Partial/XAuthorizationProvider+Policy.cs | 150 +++++----- Partial/XAuthorizationProvider+Role.cs | 14 + Partial/XAuthorizationProvider+Scope.cs | 12 + Providers/XAuthorizationProvider.cs | 340 +++++++++++++--------- Providers/XDynamicPolicyProvider.cs | 168 +++++------ xIdentityService.csproj | 9 +- 11 files changed, 664 insertions(+), 450 deletions(-) create mode 100644 Authorization/XApiKeyRoleRequirement.cs create mode 100644 Authorization/XApiKeyScopeRequirement .cs create mode 100644 Handlers/XApiKeyAuthenticationHandler.cs create mode 100644 Partial/XAuthorizationProvider+Role.cs create mode 100644 Partial/XAuthorizationProvider+Scope.cs diff --git a/Attributes/XApiKeyAccessAttribute.cs b/Attributes/XApiKeyAccessAttribute.cs index 678da5c..b2875b3 100644 --- a/Attributes/XApiKeyAccessAttribute.cs +++ b/Attributes/XApiKeyAccessAttribute.cs @@ -1,5 +1,4 @@ using System; -using System.Threading; using xCommons.Extensions; using xExceptions.Constants; using xIdentityModels.Models; @@ -12,7 +11,6 @@ using xIdentityService.Constants; using xIdentityService.Interfaces; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.DependencyInjection; namespace xIdentityService.Attributes @@ -22,7 +20,7 @@ namespace xIdentityService.Attributes AllowMultiple = false, Inherited = true )] - public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter + public class XApiKeyAccessAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter { /// /// Optional allowed scopes. If empty, no scope enforcement. @@ -41,51 +39,27 @@ namespace xIdentityService.Attributes // Scopes = scopes; + + // + Policy = $"{XIdentityServiceConstants.PolicyCacheKeyPrefix}:{string.Join(";", Scopes)}"; } /// /// Authorization Filtering ... /// /// - public void OnAuthorization(AuthorizationFilterContext context) - { - Task.FromResult(OnAuthorizationAsync(context)); - } - - /// - /// Handle Authorization Filtering Using Tasks ... - /// - /// - /// - /// - private async Task OnAuthorizationAsync( - AuthorizationFilterContext context, - CancellationToken cancellationToken = default - ) + public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { // // Access HttpContext ... var http = context.HttpContext; + var cancellationToken = http.RequestAborted; var error = XException.NotAuthorized.ToXError(); var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue(); // try { - // - // Obtain the endpoint currently being executed - var endpointFeature = http.Features.Get(); - var endpoint = endpointFeature?.Endpoint; - if (endpoint.IsNull() || - endpointFeature.IsNull() - ) - { - // - error.Message = "Endpoint not Accessible ..."; - context.Result = new UnauthorizedObjectResult(error); - return; - } - // // Retrieve Identity Provider Service from DI ... var identityService = http.RequestServices diff --git a/Authorization/XApiKeyRoleRequirement.cs b/Authorization/XApiKeyRoleRequirement.cs new file mode 100644 index 0000000..188cee4 --- /dev/null +++ b/Authorization/XApiKeyRoleRequirement.cs @@ -0,0 +1,41 @@ +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; +using Microsoft.AspNetCore.Authorization; + +namespace xIdentityService.Authorization +{ + public class XApiKeyRoleRequirement : IAuthorizationRequirement + { + public IReadOnlyCollection Roles { get; } + public XApiKeyRoleRequirement(IEnumerable roles) + { + Roles = [.. roles ?? []]; + } + } + + public class XApiKeyRoleHandler : AuthorizationHandler + { + protected override Task HandleRequirementAsync( + AuthorizationHandlerContext context, + XApiKeyRoleRequirement requirement + ) + { + // + if (!requirement.Roles.Any()) + { + context.Succeed(requirement); + return Task.CompletedTask; + } + + // + if (requirement.Roles.Any(context.User.IsInRole)) + { + context.Succeed(requirement); + } + + // + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/Authorization/XApiKeyScopeRequirement .cs b/Authorization/XApiKeyScopeRequirement .cs new file mode 100644 index 0000000..f23cf4c --- /dev/null +++ b/Authorization/XApiKeyScopeRequirement .cs @@ -0,0 +1,54 @@ +using System; +using System.Linq; +using IdentityModel; +using System.Threading.Tasks; +using System.Collections.Generic; +using Microsoft.AspNetCore.Authorization; + +namespace xIdentityService.Authorization +{ + public class XApiKeyScopeRequirement : IAuthorizationRequirement + { + public IReadOnlyCollection Scopes { get; } + + public XApiKeyScopeRequirement(IEnumerable scopes) + { + Scopes = [.. scopes ?? []]; + } + } + + public class XApiKeyScopeHandler : AuthorizationHandler + { + protected override Task HandleRequirementAsync( + AuthorizationHandlerContext context, + XApiKeyScopeRequirement requirement + ) + { + // + if (!requirement.Scopes.Any()) + { + // + context.Succeed(requirement); + return Task.CompletedTask; + } + + // + var userScopes = new HashSet( + context.User + .FindAll(JwtClaimTypes.Scope) + .SelectMany(c => c.Value.Split([' '], StringSplitOptions.RemoveEmptyEntries)), + StringComparer.OrdinalIgnoreCase + ); + + // + if (requirement.Scopes.All(s => userScopes.Contains(s))) + { + context.Succeed(requirement); + } + + // + return Task.CompletedTask; + } + } + +} \ No newline at end of file diff --git a/Handlers/XApiKeyAuthenticationHandler.cs b/Handlers/XApiKeyAuthenticationHandler.cs new file mode 100644 index 0000000..1b49f16 --- /dev/null +++ b/Handlers/XApiKeyAuthenticationHandler.cs @@ -0,0 +1,66 @@ +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 + { + private readonly IXIdentityProvider identityProvider; + + public XApiKeyAuthenticationHandler( + UrlEncoder encoder, + ILoggerFactory logger, + ISystemClock systemClock, + IXIdentityProvider identityProvider, + IOptionsMonitor options + ) : base(options, logger, encoder, systemClock) + { + this.identityProvider = identityProvider; + } + + protected override async Task 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))); + } + } +} \ No newline at end of file diff --git a/Interfaces/IXAuthorizationProvider.cs b/Interfaces/IXAuthorizationProvider.cs index 769c9fc..fdae64e 100644 --- a/Interfaces/IXAuthorizationProvider.cs +++ b/Interfaces/IXAuthorizationProvider.cs @@ -1,115 +1,115 @@ -// using xModels.Dtos; -// using System.Threading; -// using xIdentityModels.Dtos; -// using System.Threading.Tasks; -// using xIdentityModels.Models; -// using System.Collections.Generic; -// using xIdentityService.Models; +using xModels.Dtos; +using System.Threading; +using xIdentityModels.Dtos; +using System.Threading.Tasks; +using xIdentityModels.Models; +using xIdentityService.Models; +using System.Collections.Generic; -// namespace xIdentityService.Interfaces -// { -// public interface IXAuthorizationProvider -// { -// // -// #region Scope ... -// Task> QueryScopesAsync( -// XQuery query, -// CancellationToken cancellationToken = default -// ); -// Task GetScopeAsync( -// string name, -// CancellationToken cancellationToken = default -// ); -// Task AddScopeAsync( -// XScopeDefinitionDto item, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// Task UpdateScopeAsync( -// string name, -// XScopeDefinitionDto item, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// Task RemoveScopeAsync( -// string name, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// #endregion +namespace xIdentityService.Interfaces +{ + public interface IXAuthorizationProvider + { + // + #region Scope ... + Task> QueryScopesAsync( + XQuery query, + CancellationToken cancellationToken = default + ); + Task GetScopeAsync( + string name, + CancellationToken cancellationToken = default + ); + Task AddScopeAsync( + XScopeDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + Task UpdateScopeAsync( + string name, + XScopeDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + Task RemoveScopeAsync( + string name, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + #endregion -// // -// #region Role ... -// Task> GetRolesAsync( -// CancellationToken cancellationToken = default -// ); -// Task GetRoleAsync( -// string name, -// CancellationToken cancellationToken = default -// ); -// Task AddRoleAsync( -// XRoleDefinitionDto item, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// Task UpdateRoleAsync( -// string name, -// XRoleDefinitionDto item, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// Task RemoveRoleAsync( -// string name, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// Task CountUsersInRoleAsync( -// string name, -// CancellationToken cancellationToken = default -// ); -// #endregion + // + #region Role ... + Task> GetRolesAsync( + CancellationToken cancellationToken = default + ); + Task GetRoleAsync( + string name, + CancellationToken cancellationToken = default + ); + Task AddRoleAsync( + XRoleDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + Task UpdateRoleAsync( + string name, + XRoleDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + Task RemoveRoleAsync( + string name, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + Task CountUsersInRoleAsync( + string name, + CancellationToken cancellationToken = default + ); + #endregion -// // -// #region Policy ... -// Task> QueryPoliciesAsync( -// XQuery query, -// CancellationToken cancellationToken = default -// ); -// Task GetPolicyAsync( -// string name, -// CancellationToken cancellationToken = default -// ); -// Task AddPolicyAsync( -// XPolicyDefinitionDto item, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// Task UpdatePolicyAsync( -// string name, -// XPolicyDefinitionDto item, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// Task RemovePolicyAsync( -// string name, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ); -// Task EvaluatePolicyAsync( -// string name, -// XUserClaimsInfoDto target, -// CancellationToken cancellationToken = default -// ); -// Task GetEffectiveAuthorizationAsync( -// XUserClaimsInfoDto target, -// CancellationToken cancellationToken = default -// ); -// #endregion + // + #region Policy ... + Task> QueryPoliciesAsync( + XQuery query, + CancellationToken cancellationToken = default + ); + Task GetPolicyAsync( + string name, + CancellationToken cancellationToken = default + ); + Task AddPolicyAsync( + XPolicyDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + Task UpdatePolicyAsync( + string name, + XPolicyDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + Task RemovePolicyAsync( + string name, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ); + Task EvaluatePolicyAsync( + string name, + XUserClaimsInfoDto target, + CancellationToken cancellationToken = default + ); + Task GetEffectiveAuthorizationAsync( + XUserClaimsInfoDto target, + CancellationToken cancellationToken = default + ); + #endregion -// // -// #region Utilities ... -// Task SyncAllAsync(CancellationToken cancellationToken = default); -// Task InvalidateAsync(string policyName = null); -// #endregion -// } -// } \ No newline at end of file + // + #region Utilities ... + Task SyncAllAsync(CancellationToken cancellationToken = default); + Task InvalidateAsync(string policyName = null); + #endregion + } +} \ No newline at end of file diff --git a/Partial/XAuthorizationProvider+Policy.cs b/Partial/XAuthorizationProvider+Policy.cs index c09e64d..1ce74c2 100644 --- a/Partial/XAuthorizationProvider+Policy.cs +++ b/Partial/XAuthorizationProvider+Policy.cs @@ -1,86 +1,86 @@ -// using System.Threading; -// using xCommons.Extensions; -// using xIdentityModels.Dtos; -// using xExceptions.Constants; -// using System.Threading.Tasks; -// using xIdentityModels.Models; +using System.Threading; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xIdentityModels.Models; -// namespace xIdentityService.Providers -// { -// public partial class XAuthorizationProvider -// { -// // -// #region Policy ... -// public async Task AddPolicyAsync( -// XPolicyDefinitionDto item, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ) -// { -// // -// // Validate ... -// if (item.IsNull() || item.Name.IsNullOrEmpty()) -// { -// XException.InvalidArgs.Throw(); -// } +namespace xIdentityService.Providers +{ + public partial class XAuthorizationProvider + { + // + #region Policy ... + public async Task AddPolicyAsync( + XPolicyDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (item.IsNull() || item.Name.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } -// // -// var normalized = item.Name.ToNormalString(); -// var exists = await policies.FindOneAsync( -// predicate: p => p.Name.ToLower() == normalized, -// cancellationToken: cancellationToken -// ); -// if (!exists.IsNull()) -// { -// XException.Duplicate.Throw(); -// } + // + var normalized = item.Name.ToNormalString(); + var exists = await policies.FindOneAsync( + predicate: p => p.Name.ToLower() == normalized, + cancellationToken: cancellationToken + ); + if (!exists.IsNull()) + { + XException.Duplicate.Throw(); + } -// // -// await ValidateReferencesAsync(item, cancellationToken); + // + await ValidateReferencesAsync(item, cancellationToken); -// // -// item.IsSystem = false; + // + item.IsSystem = false; -// // -// var result = await policies.AddAsync( -// item: item, -// cancellationToken: cancellationToken -// ); + // + var result = await policies.AddAsync( + item: item, + cancellationToken: cancellationToken + ); -// // -// await InvalidateAsync(result.Name); + // + await InvalidateAsync(result.Name); -// // -// return await ToDtoWithEffectiveRolesAsync(result, cancellationToken); -// } + // + return await ToDtoWithEffectiveRolesAsync(result, cancellationToken); + } -// public async Task RemovePolicyAsync( -// string name, -// XUserClaimsInfoDto userInfo, -// CancellationToken cancellationToken = default -// ) -// { -// // -// var entity = await FindPolicyOrThrowAsync(name, cancellationToken); -// if (entity.IsSystem) -// { -// XException.NotAllowed.Throw(); -// } + public async Task RemovePolicyAsync( + string name, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + var entity = await FindPolicyOrThrowAsync(name, cancellationToken); + if (entity.IsSystem) + { + XException.NotAllowed.Throw(); + } -// // -// await policies.RemoveAsync( -// id: entity.Id, -// cancellationToken: cancellationToken -// ); + // + await policies.RemoveAsync( + id: entity.Id, + cancellationToken: cancellationToken + ); -// // -// await InvalidateAsync(entity.Name); -// return true; -// } -// #endregion + // + await InvalidateAsync(entity.Name); + return true; + } + #endregion -// // -// #region Private ... -// #endregion -// } -// } \ No newline at end of file + // + #region Private ... + #endregion + } +} \ No newline at end of file diff --git a/Partial/XAuthorizationProvider+Role.cs b/Partial/XAuthorizationProvider+Role.cs new file mode 100644 index 0000000..f0bb462 --- /dev/null +++ b/Partial/XAuthorizationProvider+Role.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace xIdentityService.Providers +{ + public partial class XAuthorizationProvider + { + // + #region Role ... + #endregion + } +} \ No newline at end of file diff --git a/Partial/XAuthorizationProvider+Scope.cs b/Partial/XAuthorizationProvider+Scope.cs new file mode 100644 index 0000000..cdc3e3d --- /dev/null +++ b/Partial/XAuthorizationProvider+Scope.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace xIdentityService.Providers +{ + public partial class XAuthorizationProvider + { + + } +} \ No newline at end of file diff --git a/Providers/XAuthorizationProvider.cs b/Providers/XAuthorizationProvider.cs index 72caf9f..bd0319e 100644 --- a/Providers/XAuthorizationProvider.cs +++ b/Providers/XAuthorizationProvider.cs @@ -1,156 +1,208 @@ -// using System.Linq; -// using System.Threading; -// using xCommons.Extensions; -// using xIdentityModels.Dtos; -// using xExceptions.Constants; -// using System.Threading.Tasks; -// using xIdentityService.Interfaces; +using System.Threading; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xIdentityService.Interfaces; +using System.Collections.Generic; +using System.Linq; +using System; +using xIdentityModels.Models; -// // -// // TODO: Remove this to xIds ... -// namespace xIdentityService.Providers -// { -// public partial class XAuthorizationProvider : IXAuthorizationProvider -// { -// // -// private readonly IXRoleProvider roles; -// private readonly IXScopeProvider scopes; -// private readonly IXPolicyProvider policies; -// private readonly IXRoleSyncService roleSync; -// private readonly IXAuthorizationCache cache; -// private readonly IXScopeSyncService scopeSync; -// private readonly IXRoleHierarchyResolver resolver; -// // private readonly IXEventServiceProvider eventService; +// +// TODO: Remove this to xIds ... +namespace xIdentityService.Providers +{ + public partial class XAuthorizationProvider : IXAuthorizationProvider + { + // + private readonly IXRoleProvider roles; + private readonly IXScopeProvider scopes; + private readonly IXPolicyProvider policies; + private readonly IXRoleSyncService roleSync; + private readonly IXAuthorizationCache cache; + private readonly IXScopeSyncService scopeSync; + private readonly IXRoleHierarchyResolver resolver; + // private readonly IXEventServiceProvider eventService; -// public XAuthorizationProvider( -// IXRoleProvider roles, -// IXScopeProvider scopes, -// IXPolicyProvider policies, -// IXRoleSyncService roleSync, -// IXAuthorizationCache cache, -// IXScopeSyncService scopeSync, -// IXRoleHierarchyResolver resolver -// ) -// { -// // -// this.roles = roles; -// this.cache = cache; -// this.scopes = scopes; -// this.policies = policies; -// this.roleSync = roleSync; -// this.resolver = resolver; -// this.scopeSync = scopeSync; -// } + public XAuthorizationProvider( + IXRoleProvider roles, + IXScopeProvider scopes, + IXPolicyProvider policies, + IXRoleSyncService roleSync, + IXAuthorizationCache cache, + IXScopeSyncService scopeSync, + IXRoleHierarchyResolver resolver + ) + { + // + this.roles = roles; + this.cache = cache; + this.scopes = scopes; + this.policies = policies; + this.roleSync = roleSync; + this.resolver = resolver; + this.scopeSync = scopeSync; + } -// // -// #region Commons ... -// /// -// /// Clear Local Cache and Notify other Instances ... -// /// -// public async Task InvalidateAsync(string policyName = null) -// { -// // -// if (policyName.IsNullOrEmpty()) -// { -// cache.Clear(); -// } -// else -// { -// cache.RemovePolicy(policyName); -// } -// } -// #endregion + // + #region Commons ... + /// + /// Clear Local Cache and Notify other Instances ... + /// + public async Task InvalidateAsync(string policyName = null) + { + // + if (policyName.IsNullOrEmpty()) + { + cache.Clear(); + } + else + { + cache.RemovePolicy(policyName); + } + } + #endregion -// // -// #region Private ... -// private async Task FindPolicyOrThrowAsync( -// string name, -// CancellationToken cancellationToken -// ) -// { -// // -// if (name.IsNullOrEmpty()) -// { -// XException.InvalidArgs.Throw(); -// } + // + #region Private ... + private async Task FindPolicyOrThrowAsync( + string name, + CancellationToken cancellationToken + ) + { + // + if (name.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } -// // -// var normalized = name.ToNormalString(); -// var result = await policies.FindOneAsync( -// predicate: p => p.Name.ToLower() == normalized, -// cancellationToken: cancellationToken -// ); -// if (result.IsNull()) -// { -// XException.NotFound.Throw(); -// } + // + var normalized = name.ToNormalString(); + var result = await policies.FindOneAsync( + predicate: p => p.Name.ToLower() == normalized, + cancellationToken: cancellationToken + ); + if (result.IsNull()) + { + XException.NotFound.Throw(); + } -// // -// return result; -// } + // + return result; + } -// // private async Task ValidateReferencesAsync( -// // XPolicyDefinitionDto item, -// // CancellationToken cancellationToken -// // ) -// // { -// // // -// // // Referenced Roles must exist ... -// // if (item.RequiredRoles.HasChild()) -// // { -// // var all = (await roles.GetAllAsync(cancellationToken: cancellationToken)) -// // .Select(r => r.Name.ToNormalString()).ToList(); -// // if (item.RequiredRoles.Any(r => !all.Contains(r.ToNormalString()))) -// // { -// // XException.NotFound.Throw(); -// // } -// // } + private async Task ValidateReferencesAsync( + XPolicyDefinitionDto item, + CancellationToken cancellationToken + ) + { + // + // Defensive guard ... + if (item.IsNull()) + { + XException.InvalidArgs.Throw(); + } -// // // -// // // Referenced Scopes must exist ... -// // if (item.RequiredScopes.HasChild()) -// // { -// // var all = (await scopes.GetAllAsync(cancellationToken: cancellationToken)) -// // .Select(s => s.Name.ToNormalString()).ToList(); -// // if (item.RequiredScopes.Any(s => !all.Contains(s.ToNormalString()))) -// // { -// // XException.NotFound.Throw(); -// // } -// // } -// // } + // + // The DTO stores RequiredRoles / RequiredScopes as CSV strings. + // Parse them into collections ONCE (ParseListString NREs on a null + // string, so guard first) ... -// // private async Task ToDtoWithEffectiveRolesAsync( -// // XPolicyDefinition entity, -// // CancellationToken cancellationToken -// // ) -// // { -// // // -// // var dto = entity.ToDto(); -// // dto.EffectiveRoles = (await resolver.ResolveEffectiveRolesAsync( -// // explicitRoles: entity.RequiredRoles.ToCsvList(), -// // minRoleWeight: entity.MinRoleWeight, -// // cancellationToken: cancellationToken -// // )).ToList(); + // + var requiredRoles = item.RequiredRoles.IsNullOrEmpty() + ? [] + : item.RequiredRoles.ParseListString().ToList(); -// // // -// // return dto; -// // } + // + var requiredScopes = item.RequiredScopes.IsNullOrEmpty() + ? [] + : item.RequiredScopes.ParseListString().ToList(); -// // private async Task ToDtoWithEffectiveRolesAsync( -// // XPolicyDefinitionDto item, -// // CancellationToken cancellationToken = default -// // ) -// // { -// // // -// // item.EffectiveRoles = (await resolver.ResolveEffectiveRolesAsync( -// // minRoleWeight: item.MinRoleWeight, -// // cancellationToken: cancellationToken, -// // explicitRoles: item.RequiredRoles.ParseListString() -// // )).ToList(); + // + // Referenced Roles must exist ... + if (requiredRoles.HasChild()) + { + // + var existingRoles = new HashSet( + (await roles.GetAllAsync(cancellationToken: cancellationToken)) + .Select(r => r.Name.ToNormalString()), + StringComparer.OrdinalIgnoreCase + ); + if (requiredRoles.Any(r => !existingRoles.Contains(r.ToNormalString()))) + { + XException.NotFound.Throw(); + } + } -// // // -// // return item; -// // } -// #endregion -// } -// } \ No newline at end of file + // + // Referenced Scopes must exist ... + if (requiredScopes.HasChild()) + { + // + var existingScopes = new HashSet( + (await scopes.GetAllAsync(cancellationToken: cancellationToken)) + .Select(s => s.Name.ToNormalString()), + StringComparer.OrdinalIgnoreCase + ); + if (requiredScopes.Any(s => !existingScopes.Contains(s.ToNormalString()))) + { + XException.NotFound.Throw(); + } + } + } + + private async Task ToDtoWithEffectiveRolesAsync( + XPolicyDefinitionDto item, + CancellationToken cancellationToken = default + ) + { + // + // Parse the DTO's CSV-string RequiredRoles. ParseListString NREs on a + // null string, so guard first; the resolver itself is null-safe on an + // empty explicitRoles set ... + var explicitRoles = item.RequiredRoles.IsNullOrEmpty() + ? null + : item.RequiredRoles.ParseListString(); + + // + item.EffectiveRoles = ( + await resolver.ResolveEffectiveRolesAsync( + explicitRoles: explicitRoles, + minRoleWeight: item.MinRoleWeight, + cancellationToken: cancellationToken + ) + ).ToList(); + + // + return item; + } + + private async Task ToDtoWithEffectiveRolesAsync( + XPolicyDefinition entity, + CancellationToken cancellationToken + ) + { + // + // Entity -> DTO (the RequiredRoles collection is serialized to the + // CSV string on the DTO by the ToDto mapping) ... + var dto = entity.ToDto(); + + // + // Effective Roles = explicit RequiredRoles U roles by MinRoleWeight + // U parent chain. explicitRoles takes IEnumerable, so pass + // the entity's collection directly (the resolver is null-safe on it) ... + dto.EffectiveRoles = ( + await resolver.ResolveEffectiveRolesAsync( + explicitRoles: entity.RequiredRoles, + minRoleWeight: entity.MinRoleWeight, + cancellationToken: cancellationToken + ) + ).ToList(); + + // + return dto; + } + #endregion + } +} \ No newline at end of file diff --git a/Providers/XDynamicPolicyProvider.cs b/Providers/XDynamicPolicyProvider.cs index 8934009..c118fb4 100644 --- a/Providers/XDynamicPolicyProvider.cs +++ b/Providers/XDynamicPolicyProvider.cs @@ -1,94 +1,94 @@ -// using xCommons.Extensions; -// using System.Threading.Tasks; -// using xIdentityService.Interfaces; -// using xIdentityService.Extensions; -// using Microsoft.Extensions.Options; -// using Microsoft.AspNetCore.Authorization; -// using Microsoft.Extensions.DependencyInjection; +using xCommons.Extensions; +using System.Threading.Tasks; +using xIdentityService.Interfaces; +using xIdentityService.Extensions; +using Microsoft.Extensions.Options; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.DependencyInjection; -// namespace xIdentityService.Providers -// { -// /// -// /// Resolve Policies from Cache → Repository → Default (static) Provider ... -// /// -// public class XDynamicPolicyProvider : IAuthorizationPolicyProvider -// { -// private readonly IXAuthorizationCache cache; -// private readonly IServiceScopeFactory scopeFactory; -// private readonly DefaultAuthorizationPolicyProvider fallback; +namespace xIdentityService.Providers +{ + /// + /// Resolve Policies from Cache → Repository → Default (static) Provider ... + /// + public class XDynamicPolicyProvider : IAuthorizationPolicyProvider + { + private readonly IXAuthorizationCache cache; + private readonly IServiceScopeFactory scopeFactory; + private readonly DefaultAuthorizationPolicyProvider fallback; -// public XDynamicPolicyProvider( -// IXAuthorizationCache cache, -// IServiceScopeFactory scopeFactory, -// IOptions options -// ) -// { -// // -// this.cache = cache; -// this.scopeFactory = scopeFactory; -// fallback = new DefaultAuthorizationPolicyProvider(options); -// } + public XDynamicPolicyProvider( + IXAuthorizationCache cache, + IServiceScopeFactory scopeFactory, + IOptions options + ) + { + // + this.cache = cache; + this.scopeFactory = scopeFactory; + fallback = new DefaultAuthorizationPolicyProvider(options); + } -// public Task GetDefaultPolicyAsync() => -// fallback.GetDefaultPolicyAsync(); + public Task GetDefaultPolicyAsync() => + fallback.GetDefaultPolicyAsync(); -// public async Task GetPolicyAsync(string policyName) -// { -// // -// if (policyName.IsNullOrEmpty()) -// { -// return await fallback.GetPolicyAsync(policyName); -// } + public async Task GetPolicyAsync(string policyName) + { + // + if (policyName.IsNullOrEmpty()) + { + return await fallback.GetPolicyAsync(policyName); + } -// // -// // 1. Cache ... -// if (cache.TryGetPolicy(policyName, out var cached)) -// { -// return cached; -// } + // + // 1. Cache ... + if (cache.TryGetPolicy(policyName, out var cached)) + { + return cached; + } -// // -// // 2. Repository (needs a Scope because Provider is Singleton) ... -// using (var scope = scopeFactory.CreateScope()) -// { -// // -// var repository = scope.ServiceProvider.GetService(); -// var resolver = scope.ServiceProvider.GetService(); + // + // 2. Repository (needs a Scope because Provider is Singleton) ... + using (var scope = scopeFactory.CreateScope()) + { + // + var repository = scope.ServiceProvider.GetService(); + var resolver = scope.ServiceProvider.GetService(); -// // -// if (!repository.IsNull() && !resolver.IsNull()) -// { -// // -// var normalized = policyName.ToNormalString(); -// var definition = await repository.FindOneAsync( -// predicate: p => p.IsEnabled && p.Name.ToLower() == normalized -// ); + // + if (!repository.IsNull() && !resolver.IsNull()) + { + // + var normalized = policyName.ToNormalString(); + var definition = await repository.FindOneAsync( + predicate: p => p.IsEnabled && p.Name.ToLower() == normalized + ); -// // -// var requiredRoles = definition.RequiredRoles -// .ParseListString(); -// if (!definition.IsNull()) -// { -// // -// var roles = await resolver.ResolveEffectiveRolesAsync( -// explicitRoles: requiredRoles, -// minRoleWeight: definition.MinRoleWeight -// ); + // + var requiredRoles = definition.RequiredRoles + .ParseListString(); + if (!definition.IsNull()) + { + // + var roles = await resolver.ResolveEffectiveRolesAsync( + explicitRoles: requiredRoles, + minRoleWeight: definition.MinRoleWeight + ); -// // -// var policy = definition.ToAuthorizationPolicy(roles); -// if (!policy.IsNull()) -// { -// cache.SetPolicy(policyName, policy); -// return policy; -// } -// } -// } -// } + // + var policy = definition.ToAuthorizationPolicy(roles); + if (!policy.IsNull()) + { + cache.SetPolicy(policyName, policy); + return policy; + } + } + } + } -// // -// // 3. Fallback to Static Policies (LocalApi.PolicyName, XPolicies.*) ... -// return await fallback.GetPolicyAsync(policyName); -// } -// } -// } \ No newline at end of file + // + // 3. Fallback to Static Policies (LocalApi.PolicyName, XPolicies.*) ... + return await fallback.GetPolicyAsync(policyName); + } + } +} \ No newline at end of file diff --git a/xIdentityService.csproj b/xIdentityService.csproj index e7180d0..84864b6 100644 --- a/xIdentityService.csproj +++ b/xIdentityService.csproj @@ -20,8 +20,7 @@ - + @@ -36,9 +35,11 @@ - + + + +