From bdc8791822a9c3e60f86c9939b887b2fb1af09ee Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 26 Nov 2026 19:36:49 +0330 Subject: [PATCH] last ... --- DI/XDIHelperExtension.cs | 18 +- Interfaces/IXAuthorizationProvider.cs | 1 - Interfaces/IXSyncService.cs | 49 --- Partial/XAuthorizationProvider+Policy.cs | 476 ++++++++++++----------- Partial/XAuthorizationProvider+Role.cs | 290 +++++++------- Partial/XAuthorizationProvider+Scope.cs | 278 ++++++------- Providers/XAuthorizationProvider.cs | 467 ++++++++++------------ Providers/XDynamicPolicyProvider.cs | 94 ----- 8 files changed, 752 insertions(+), 921 deletions(-) delete mode 100644 Interfaces/IXSyncService.cs delete mode 100644 Providers/XDynamicPolicyProvider.cs diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index bd96d6c..17431ff 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -1,6 +1,8 @@ using System; using xCommons.Extensions; +using xExceptions.Constants; using xCommons.Authorization; +using xHttpService.Interfaces; using Microsoft.AspNetCore.Http; using xIdentityService.Security; using xIdentityService.Constants; @@ -12,8 +14,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using IdentityModel.AspNetCore.OAuth2Introspection; -using xHttpService.Interfaces; -using xExceptions.Constants; namespace xIdentityService.DI { @@ -150,21 +150,21 @@ namespace xIdentityService.DI var roles = source.GetRegisteredService(); var scopes = source.GetRegisteredService(); var policies = source.GetRegisteredService(); - var roleSync = source.GetRegisteredService(); var cache = source.GetRegisteredService(); - var scopeSync = source.GetRegisteredService(); var resolver = source.GetRegisteredService(); + // var roleSync = source.GetRegisteredService(); + // var scopeSync = source.GetRegisteredService(); // - var isValid = + var isInvalid = roles.IsNull() || cache.IsNull() || scopes.IsNull() || policies.IsNull() || - roleSync.IsNull() || - resolver.IsNull() || - scopeSync.IsNull(); - if (!isValid) + resolver.IsNull(); + // roleSync.IsNull() || + // scopeSync.IsNull(); + if (isInvalid) { XException.InvalidConfiguration.Throw(); } diff --git a/Interfaces/IXAuthorizationProvider.cs b/Interfaces/IXAuthorizationProvider.cs index fdae64e..17ddb5c 100644 --- a/Interfaces/IXAuthorizationProvider.cs +++ b/Interfaces/IXAuthorizationProvider.cs @@ -108,7 +108,6 @@ namespace xIdentityService.Interfaces // #region Utilities ... - Task SyncAllAsync(CancellationToken cancellationToken = default); Task InvalidateAsync(string policyName = null); #endregion } diff --git a/Interfaces/IXSyncService.cs b/Interfaces/IXSyncService.cs deleted file mode 100644 index 509a427..0000000 --- a/Interfaces/IXSyncService.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; - -namespace xIdentityService.Interfaces -{ - /// - /// Implemented on xIds over IdentityServer4 ConfigurationDbContext ... - /// - public interface IXScopeSyncService - { - Task UpsertAsync( - XScopeDefinition scope, - CancellationToken cancellationToken = default - ); - Task RemoveAsync( - string scopeName, - CancellationToken cancellationToken = default - ); - Task IsApiResourceExistsAsync( - string apiResourceName, - CancellationToken cancellationToken = default - ); - } - - /// - /// Implemented on xIds over RoleManager<IdentityRole> ... - /// - public interface IXRoleSyncService - { - Task UpsertAsync( - XRoleDefinition role, - CancellationToken cancellationToken = default - ); - Task RemoveAsync( - string roleName, - CancellationToken cancellationToken = default - ); - Task CountUsersInRoleAsync( - string roleName, - CancellationToken cancellationToken = default - ); - Task> GetUserRolesAsync( - string userSelectByParam, - CancellationToken cancellationToken = default - ); - } -} \ No newline at end of file diff --git a/Partial/XAuthorizationProvider+Policy.cs b/Partial/XAuthorizationProvider+Policy.cs index b929ada..88f14f3 100644 --- a/Partial/XAuthorizationProvider+Policy.cs +++ b/Partial/XAuthorizationProvider+Policy.cs @@ -15,273 +15,283 @@ 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(); - } + // // + // #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 result; - } + // // + // return result; + // } - 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; - } + // // + // await InvalidateAsync(entity.Name); + // return true; + // } - public async Task> QueryPoliciesAsync( - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (query.IsNull()) - { - XException.InvalidArgs.Throw(); - } + // public async Task> QueryPoliciesAsync( + // XQuery query, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Validate ... + // if (query.IsNull()) + // { + // XException.InvalidArgs.Throw(); + // } - // - var result = await policies.QueryAsync( - query: query, - cancellationToken: cancellationToken - ); + // // + // var result = await policies.QueryAsync( + // query: query, + // cancellationToken: cancellationToken + // ); - // - return result; - } + // // + // return result; + // } - public async Task GetPolicyAsync( - string name, - CancellationToken cancellationToken = default - ) - { - // - var result = await FindPolicyOrThrowAsync(name, cancellationToken); + // public async Task GetPolicyAsync( + // string name, + // CancellationToken cancellationToken = default + // ) + // { + // // + // var result = await FindPolicyOrThrowAsync(name, cancellationToken); - // - return result; - } + // // + // return result; + // } - public async Task UpdatePolicyAsync( - string name, - XPolicyDefinitionDto item, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (name.IsNullOrEmpty() || item.IsNull()) - { - XException.InvalidArgs.Throw(); - } + // public async Task UpdatePolicyAsync( + // string name, + // XPolicyDefinitionDto item, + // XUserClaimsInfoDto userInfo, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Validate ... + // if (name.IsNullOrEmpty() || item.IsNull()) + // { + // XException.InvalidArgs.Throw(); + // } - // - var exists = await FindPolicyOrThrowAsync(name, cancellationToken); - if (exists.IsSystem) - { - XException.NotAllowed.Throw(); - } + // // + // var exists = await FindPolicyOrThrowAsync(name, cancellationToken); + // if (exists.IsSystem) + // { + // XException.NotAllowed.Throw(); + // } - // - // Referenced Roles & Scopes must exist ... - await ValidateReferencesAsync(item, cancellationToken); + // // + // // Referenced Roles & Scopes must exist ... + // await ValidateReferencesAsync(item, cancellationToken); - // - var result = await policies.UpdateAsync( - item: item, - id: exists.Id, - userInfo: userInfo, - cancellationToken: cancellationToken - ); + // // + // var result = await policies.UpdateAsync( + // item: item, + // id: exists.Id, + // userInfo: userInfo, + // cancellationToken: cancellationToken + // ); - // - // Drop the cached policy so it rebuilds on next evaluation ... - await InvalidateAsync(result.Name); + // // + // // Drop the cached policy so it rebuilds on next evaluation ... + // await InvalidateAsync(result.Name); - // - // Return the updated DTO as-is (EffectiveRoles is not a field on - // XPolicyDefinitionDto) ... - return result; - } + // // + // // Return the updated DTO as-is (EffectiveRoles is not a field on + // // XPolicyDefinitionDto) ... + // return result; + // } - public async Task EvaluatePolicyAsync( - string name, - XUserClaimsInfoDto target, - CancellationToken cancellationToken = default - ) - { - // - // Load the policy (throws NotFound when missing) ... - var dto = await FindPolicyOrThrowAsync(name, cancellationToken); + // public async Task EvaluatePolicyAsync( + // string name, + // XUserClaimsInfoDto target, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Load the policy (throws NotFound when missing) ... + // var dto = await FindPolicyOrThrowAsync(name, cancellationToken); - // - var result = new XPolicyEvaluationResultDto - { - Passed = true, - Policy = dto.Name, - FailedRequirements = [] - }; + // // + // var result = new XPolicyEvaluationResultDto + // { + // Passed = true, + // Policy = dto.Name, + // FailedRequirements = [] + // }; - // - // Build the policy's effective authorization via the shared helper - // (resolver + projection onto XEffectiveAuthorizationDto) ... - var auth = await ToDtoWithEffectiveRolesAsync(dto, cancellationToken); - if (auth.IsNull()) - { - // - result.Passed = false; - result.FailedRequirements.Add("PolicyNotBuilt"); + // // + // // Build the policy's effective authorization via the shared helper + // // (resolver + projection onto XEffectiveAuthorizationDto) ... + // var auth = await ToDtoWithEffectiveRolesAsync(dto, cancellationToken); + // if (auth.IsNull()) + // { + // // + // result.Passed = false; + // result.FailedRequirements.Add("PolicyNotBuilt"); - // - return result; - } + // // + // return result; + // } - // - // Anonymous user fails any policy that requires authentication ... - if (target.IsNull()) - { - // - if (auth.RequireAuthenticatedUser) - { - result.Passed = false; - result.FailedRequirements.Add("RequireAuthenticatedUser"); - } + // // + // // Anonymous user fails any policy that requires authentication ... + // if (target.IsNull()) + // { + // // + // if (auth.RequireAuthenticatedUser) + // { + // // + // result.Passed = false; + // result.FailedRequirements.Add("RequireAuthenticatedUser"); + // } - // - return result; - } + // // + // return result; + // } - // - // Effective Roles: the user must hold at least one ... - if (auth.EffectiveRoles.HasChild()) - { - // - var userRoles = await roleSync.GetUserRolesAsync( - target.GetUserSelectByParam(), - cancellationToken - ); + // // + // // Effective Roles: the user must hold at least one ... + // if (auth.EffectiveRoles.HasChild()) + // { + // // + // // var userRoles = await roles.FindManyAsync( + // // target.GetUserSelectByParam(), + // // cancellationToken + // // ); - // - var matched = auth.EffectiveRoles.Any(er => - userRoles.Any(ur => - string.Equals(ur, er, StringComparison.OrdinalIgnoreCase) - ) - ); + // // + // var userSelectByParam = target.GetUserSelectByParam(); - // - if (!matched) - { - // - result.Passed = false; - result.FailedRequirements.Add("RequiredRoles"); - } - } + // // + // var userRoles = await roles.FindManyAsync( + // predicate: x => x. + // cancellationToken: cancellationToken + // ); - // - // NOTE: RequireEnabledUser (IsEnabled / !IsBanned), EffectiveScopes and - // EffectiveClaims checks are layered on here once the matching flags / - // collections on XUserClaimsInfoDto (xIdentityModels) are wired. - return result; - } + // // + // var matched = auth.EffectiveRoles.Any(er => + // userRoles.Any(ur => + // string.Equals(ur, er, StringComparison.OrdinalIgnoreCase) + // ) + // ); - public async Task GetEffectiveAuthorizationAsync( - XUserClaimsInfoDto target, - CancellationToken cancellationToken = default - ) - { - // - var result = new XEffectiveAuthorizationDto - { - RequireEnabledUser = !target.IsNull(), - RequireAuthenticatedUser = !target.IsNull(), - EffectiveClaims = new List(), - EffectiveRoles = new HashSet(StringComparer.OrdinalIgnoreCase), - EffectiveScopes = new HashSet(StringComparer.OrdinalIgnoreCase), - }; + // // + // if (!matched) + // { + // // + // result.Passed = false; + // result.FailedRequirements.Add("RequiredRoles"); + // } + // } - // - if (target.IsNull()) - { - return result; - } + // // + // // NOTE: RequireEnabledUser (IsEnabled / !IsBanned), EffectiveScopes and + // // EffectiveClaims checks are layered on here once the matching flags / + // // collections on XUserClaimsInfoDto (xIdentityModels) are wired. + // return result; + // } - // - // Effective roles = the user's actual roles (from RoleManager) ... - var userRoles = await roleSync.GetUserRolesAsync( - cancellationToken: cancellationToken, - userSelectByParam: target.GetUserSelectByParam() - ); - foreach (var role in userRoles) - { - result.EffectiveRoles.Add(role); - } + // public async Task GetEffectiveAuthorizationAsync( + // XUserClaimsInfoDto target, + // CancellationToken cancellationToken = default + // ) + // { + // // + // var result = new XEffectiveAuthorizationDto + // { + // RequireEnabledUser = !target.IsNull(), + // RequireAuthenticatedUser = !target.IsNull(), + // EffectiveClaims = new List(), + // EffectiveRoles = new HashSet(StringComparer.OrdinalIgnoreCase), + // EffectiveScopes = new HashSet(StringComparer.OrdinalIgnoreCase), + // }; - // - // NOTE: EffectiveScopes / EffectiveClaims aggregation is wired here from - // the user's scope / claim source on XUserClaimsInfoDto (xIdentityModels). - return result; - } - #endregion + // // + // if (target.IsNull()) + // { + // return result; + // } - // - #region Private ... - #endregion + // // + // // Effective roles = the user's actual roles (from RoleManager) ... + // var userRoles = await roleSync.GetUserRolesAsync( + // cancellationToken: cancellationToken, + // userSelectByParam: target.GetUserSelectByParam() + // ); + // foreach (var role in userRoles) + // { + // result.EffectiveRoles.Add(role); + // } + + // // + // // NOTE: EffectiveScopes / EffectiveClaims aggregation is wired here from + // // the user's scope / claim source on XUserClaimsInfoDto (xIdentityModels). + // return result; + // } + // #endregion + + // // + // #region Private ... + // #endregion } } \ No newline at end of file diff --git a/Partial/XAuthorizationProvider+Role.cs b/Partial/XAuthorizationProvider+Role.cs index 79560b8..6b08ce2 100644 --- a/Partial/XAuthorizationProvider+Role.cs +++ b/Partial/XAuthorizationProvider+Role.cs @@ -12,170 +12,170 @@ namespace xIdentityService.Providers public partial class XAuthorizationProvider { // - #region Role ... - public async Task> GetRolesAsync( - CancellationToken cancellationToken = default - ) - { - // - var result = await roles - .GetAllAsync(cancellationToken: cancellationToken); + // #region Role ... + // public async Task> GetRolesAsync( + // CancellationToken cancellationToken = default + // ) + // { + // // + // var result = await roles + // .GetAllAsync(cancellationToken: cancellationToken); - // - return result; - } + // // + // return result; + // } - public async Task GetRoleAsync( - string name, - CancellationToken cancellationToken = default - ) - { - // - var result = await FindRoleOrThrowAsync(name, cancellationToken); + // public async Task GetRoleAsync( + // string name, + // CancellationToken cancellationToken = default + // ) + // { + // // + // var result = await FindRoleOrThrowAsync(name, cancellationToken); - // - return result; - } + // // + // return result; + // } - public async Task AddRoleAsync( - XRoleDefinitionDto item, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (item.IsNull() || item.Name.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } + // public async Task AddRoleAsync( + // XRoleDefinitionDto item, + // XUserClaimsInfoDto userInfo, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Validate ... + // if (item.IsNull() || item.Name.IsNullOrEmpty()) + // { + // XException.InvalidArgs.Throw(); + // } - // - // Duplicate check ... - var normalized = item.Name.ToNormalString(); - var exists = await roles.FindOneAsync( - predicate: r => r.Name.ToLower() == normalized, - cancellationToken: cancellationToken - ); - if (!exists.IsNull()) - { - XException.Duplicate.Throw(); - } + // // + // // Duplicate check ... + // var normalized = item.Name.ToNormalString(); + // var exists = await roles.FindOneAsync( + // predicate: r => r.Name.ToLower() == normalized, + // cancellationToken: cancellationToken + // ); + // if (!exists.IsNull()) + // { + // XException.Duplicate.Throw(); + // } - // - // Persist ... - item.IsSystem = false; - var result = await roles.AddAsync( - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); + // // + // // Persist ... + // item.IsSystem = false; + // var result = await roles.AddAsync( + // item: item, + // userInfo: userInfo, + // cancellationToken: cancellationToken + // ); - // - // Sync to IdentityServer (RoleManager) ... - var entity = roles.AsQueryable() - .FirstOrDefault(r => r.Name.ToLower() == normalized); - if (!entity.IsNull()) - { - await roleSync.UpsertAsync(entity, cancellationToken); - } + // // + // // Sync to IdentityServer (RoleManager) ... + // var entity = roles.AsQueryable() + // .FirstOrDefault(r => r.Name.ToLower() == normalized); + // if (!entity.IsNull()) + // { + // await roleSync.UpsertAsync(entity, cancellationToken); + // } - // - await InvalidateAsync(); - return result; - } + // // + // await InvalidateAsync(); + // return result; + // } - public async Task UpdateRoleAsync( - string name, - XRoleDefinitionDto item, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (name.IsNullOrEmpty() || item.IsNull()) - { - XException.InvalidArgs.Throw(); - } + // public async Task UpdateRoleAsync( + // string name, + // XRoleDefinitionDto item, + // XUserClaimsInfoDto userInfo, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Validate ... + // if (name.IsNullOrEmpty() || item.IsNull()) + // { + // XException.InvalidArgs.Throw(); + // } - // - var existing = await FindRoleOrThrowAsync(name, cancellationToken); - if (existing.IsSystem) - { - XException.NotAllowed.Throw(); - } + // // + // var existing = await FindRoleOrThrowAsync(name, cancellationToken); + // if (existing.IsSystem) + // { + // XException.NotAllowed.Throw(); + // } - // - var updated = await roles.UpdateAsync( - id: existing.Id, - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); + // // + // var updated = await roles.UpdateAsync( + // id: existing.Id, + // item: item, + // userInfo: userInfo, + // cancellationToken: cancellationToken + // ); - // - // Sync to IdentityServer ... - var entity = roles.AsQueryable() - .FirstOrDefault(r => r.Name.ToLower() == name.ToNormalString()); - if (!entity.IsNull()) - { - await roleSync.UpsertAsync(entity, cancellationToken); - } + // // + // // Sync to IdentityServer ... + // var entity = roles.AsQueryable() + // .FirstOrDefault(r => r.Name.ToLower() == name.ToNormalString()); + // if (!entity.IsNull()) + // { + // await roleSync.UpsertAsync(entity, cancellationToken); + // } - // - await InvalidateAsync(); - return updated; - } + // // + // await InvalidateAsync(); + // return updated; + // } - public async Task RemoveRoleAsync( - string name, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken = default - ) - { - // - var exists = await FindRoleOrThrowAsync(name, cancellationToken); - if (exists.IsSystem) - { - XException.NotAllowed.Throw(); - } + // public async Task RemoveRoleAsync( + // string name, + // XUserClaimsInfoDto userInfo, + // CancellationToken cancellationToken = default + // ) + // { + // // + // var exists = await FindRoleOrThrowAsync(name, cancellationToken); + // if (exists.IsSystem) + // { + // XException.NotAllowed.Throw(); + // } - // - await roles.RemoveAsync( - id: exists.Id, - userInfo: userInfo, - cancellationToken: cancellationToken - ); + // // + // await roles.RemoveAsync( + // id: exists.Id, + // userInfo: userInfo, + // cancellationToken: cancellationToken + // ); - // - // Remove from IdentityServer ... - await roleSync.RemoveAsync(name, cancellationToken); + // // + // // Remove from IdentityServer ... + // await roleSync.RemoveAsync(name, cancellationToken); - // - await InvalidateAsync(); - return true; - } + // // + // await InvalidateAsync(); + // return true; + // } - public async Task CountUsersInRoleAsync( - string name, - CancellationToken cancellationToken = default - ) - { - // - // Fail fast if the role itself does not exist ... - await FindRoleOrThrowAsync(name, cancellationToken); + // public async Task CountUsersInRoleAsync( + // string name, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Fail fast if the role itself does not exist ... + // await FindRoleOrThrowAsync(name, cancellationToken); - // - var result = await roleSync - .CountUsersInRoleAsync( - name, - cancellationToken - ); + // // + // var result = await roleSync + // .CountUsersInRoleAsync( + // name, + // cancellationToken + // ); - // - return result; - } - #endregion + // // + // return result; + // } + // #endregion } } \ No newline at end of file diff --git a/Partial/XAuthorizationProvider+Scope.cs b/Partial/XAuthorizationProvider+Scope.cs index 0b612d9..7d8cde0 100644 --- a/Partial/XAuthorizationProvider+Scope.cs +++ b/Partial/XAuthorizationProvider+Scope.cs @@ -13,162 +13,162 @@ namespace xIdentityService.Providers { public partial class XAuthorizationProvider { - // - #region Scope ... - public async Task> QueryScopesAsync( - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - if (query.IsNull()) - { - XException.InvalidArgs.Throw(); - } + // // + // #region Scope ... + // public async Task> QueryScopesAsync( + // XQuery query, + // CancellationToken cancellationToken = default + // ) + // { + // // + // if (query.IsNull()) + // { + // XException.InvalidArgs.Throw(); + // } - // - var result = await scopes.QueryAsync( - query: query, - cancellationToken: cancellationToken - ); + // // + // var result = await scopes.QueryAsync( + // query: query, + // cancellationToken: cancellationToken + // ); - // - return result; - } + // // + // return result; + // } - public async Task GetScopeAsync( - string name, - CancellationToken cancellationToken = default - ) - { - // - var result = await FindScopeOrThrowAsync(name, cancellationToken); + // public async Task GetScopeAsync( + // string name, + // CancellationToken cancellationToken = default + // ) + // { + // // + // var result = await FindScopeOrThrowAsync(name, cancellationToken); - // - return result; - } + // // + // return result; + // } - public async Task AddScopeAsync( - XScopeDefinitionDto item, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (item.IsNull() || item.Name.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } + // public async Task AddScopeAsync( + // XScopeDefinitionDto item, + // XUserClaimsInfoDto userInfo, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Validate ... + // if (item.IsNull() || item.Name.IsNullOrEmpty()) + // { + // XException.InvalidArgs.Throw(); + // } - // - // Duplicate check ... - var normalized = item.Name.ToNormalString(); - var exists = await scopes.FindOneAsync( - cancellationToken: cancellationToken, - predicate: s => s.Name.ToLower() == normalized - ); - if (!exists.IsNull()) - { - XException.Duplicate.Throw(); - } + // // + // // Duplicate check ... + // var normalized = item.Name.ToNormalString(); + // var exists = await scopes.FindOneAsync( + // cancellationToken: cancellationToken, + // predicate: s => s.Name.ToLower() == normalized + // ); + // if (!exists.IsNull()) + // { + // XException.Duplicate.Throw(); + // } - // - // Persist ... - item.IsSystem = false; - var result = await scopes.AddAsync( - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); + // // + // // Persist ... + // item.IsSystem = false; + // var result = await scopes.AddAsync( + // item: item, + // userInfo: userInfo, + // cancellationToken: cancellationToken + // ); - // - // Sync to IdentityServer (ConfigurationDbContext) ... - var entity = scopes.AsQueryable() - .FirstOrDefault(s => s.Name.ToLower() == normalized); - if (!entity.IsNull()) - { - // - await scopeSync - .UpsertAsync(entity, cancellationToken); - } + // // + // // Sync to IdentityServer (ConfigurationDbContext) ... + // var entity = scopes.AsQueryable() + // .FirstOrDefault(s => s.Name.ToLower() == normalized); + // if (!entity.IsNull()) + // { + // // + // await scopeSync + // .UpsertAsync(entity, cancellationToken); + // } - // - await InvalidateAsync(); - return result; - } + // // + // await InvalidateAsync(); + // return result; + // } - public async Task UpdateScopeAsync( - string name, - XScopeDefinitionDto item, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (name.IsNullOrEmpty() || item.IsNull()) - { - XException.InvalidArgs.Throw(); - } + // public async Task UpdateScopeAsync( + // string name, + // XScopeDefinitionDto item, + // XUserClaimsInfoDto userInfo, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Validate ... + // if (name.IsNullOrEmpty() || item.IsNull()) + // { + // XException.InvalidArgs.Throw(); + // } - // - var existing = await FindScopeOrThrowAsync(name, cancellationToken); - if (existing.IsSystem) - { - XException.NotAllowed.Throw(); - } + // // + // var existing = await FindScopeOrThrowAsync(name, cancellationToken); + // if (existing.IsSystem) + // { + // XException.NotAllowed.Throw(); + // } - // - var updated = await scopes.UpdateAsync( - id: existing.Id, - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); + // // + // var updated = await scopes.UpdateAsync( + // id: existing.Id, + // item: item, + // userInfo: userInfo, + // cancellationToken: cancellationToken + // ); - // - // Sync to IdentityServer ... - var entity = scopes.AsQueryable() - .FirstOrDefault(s => s.Name.ToLower() == name.ToNormalString()); - if (!entity.IsNull()) - { - await scopeSync.UpsertAsync(entity, cancellationToken); - } + // // + // // Sync to IdentityServer ... + // var entity = scopes.AsQueryable() + // .FirstOrDefault(s => s.Name.ToLower() == name.ToNormalString()); + // if (!entity.IsNull()) + // { + // await scopeSync.UpsertAsync(entity, cancellationToken); + // } - // - await InvalidateAsync(); - return updated; - } + // // + // await InvalidateAsync(); + // return updated; + // } - public async Task RemoveScopeAsync( - string name, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken = default - ) - { - // - var entity = await FindScopeOrThrowAsync(name, cancellationToken); - if (entity.IsSystem) - { - XException.NotAllowed.Throw(); - } + // public async Task RemoveScopeAsync( + // string name, + // XUserClaimsInfoDto userInfo, + // CancellationToken cancellationToken = default + // ) + // { + // // + // var entity = await FindScopeOrThrowAsync(name, cancellationToken); + // if (entity.IsSystem) + // { + // XException.NotAllowed.Throw(); + // } - // - await scopes.RemoveAsync( - id: entity.Id, - userInfo: userInfo, - cancellationToken: cancellationToken - ); + // // + // await scopes.RemoveAsync( + // id: entity.Id, + // userInfo: userInfo, + // cancellationToken: cancellationToken + // ); - // - // Remove from IdentityServer ... - await scopeSync.RemoveAsync(name, cancellationToken); + // // + // // Remove from IdentityServer ... + // await scopeSync.RemoveAsync(name, cancellationToken); - // - await InvalidateAsync(); - return true; - } - #endregion + // // + // await InvalidateAsync(); + // return true; + // } + // #endregion } } \ No newline at end of file diff --git a/Providers/XAuthorizationProvider.cs b/Providers/XAuthorizationProvider.cs index 727f637..5fd4459 100644 --- a/Providers/XAuthorizationProvider.cs +++ b/Providers/XAuthorizationProvider.cs @@ -14,280 +14,245 @@ using xIdentityService.Extensions; // TODO: Remove this to xIds ... namespace xIdentityService.Providers { - public partial class XAuthorizationProvider : IXAuthorizationProvider + 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 IXRoleProvider roles; + // private readonly IXScopeProvider scopes; + // private readonly IXPolicyProvider policies; + // private readonly IXAuthorizationCache cache; + // private readonly IXRoleHierarchyResolver resolver; - 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, + // IXAuthorizationCache cache, + // IXRoleHierarchyResolver resolver + // ) + // { + // // + // this.roles = roles; + // this.cache = cache; + // this.scopes = scopes; + // this.policies = policies; + // this.resolver = resolver; + // } - // - #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); - } - } + // // + // #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 - /// - /// Re-push every Role and Scope into IdentityServer and drop the local - /// authorization cache so policies rebuild lazily on next evaluation. - /// - public async Task SyncAllAsync(CancellationToken cancellationToken = default) - { - // - // Sync all Roles to IdentityServer (RoleManager) ... - foreach (var role in roles.AsQueryable()) - { - // - await roleSync - .UpsertAsync(role, cancellationToken); - } + // // + // #region Private ... + // private async Task FindRoleOrThrowAsync( + // string name, + // CancellationToken cancellationToken + // ) + // { + // // + // if (name.IsNullOrEmpty()) + // { + // XException.InvalidArgs.Throw(); + // } - // - // Sync all Scopes to IdentityServer (ConfigurationDbContext) ... - foreach (var scope in scopes.AsQueryable()) - { - // - await scopeSync - .UpsertAsync(scope, cancellationToken); - } + // // + // var normalized = name.ToNormalString(); + // var result = await roles.FindOneAsync( + // predicate: r => r.Name.ToLower() == normalized, + // cancellationToken: cancellationToken + // ); + // if (result.IsNull()) + // { + // XException.NotFound.Throw(); + // } - // - // Drop local authorization cache ... - await InvalidateAsync(); - } - #endregion + // // + // return result; + // } - // - #region Private ... - private async Task FindRoleOrThrowAsync( - string name, - CancellationToken cancellationToken - ) - { - // - if (name.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } + // private async Task FindScopeOrThrowAsync( + // string name, + // CancellationToken cancellationToken + // ) + // { + // // + // if (name.IsNullOrEmpty()) + // { + // XException.InvalidArgs.Throw(); + // } - // - var normalized = name.ToNormalString(); - var result = await roles.FindOneAsync( - predicate: r => r.Name.ToLower() == normalized, - cancellationToken: cancellationToken - ); - if (result.IsNull()) - { - XException.NotFound.Throw(); - } + // // + // var normalized = name.ToNormalString(); + // var result = await scopes.FindOneAsync( + // predicate: s => s.Name.ToLower() == normalized, + // cancellationToken: cancellationToken + // ); + // if (result.IsNull()) + // { + // XException.NotFound.Throw(); + // } - // - return result; - } + // // + // return result; + // } - private async Task FindScopeOrThrowAsync( - string name, - CancellationToken cancellationToken - ) - { - // - if (name.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } + // private async Task FindPolicyOrThrowAsync( + // string name, + // CancellationToken cancellationToken + // ) + // { + // // + // if (name.IsNullOrEmpty()) + // { + // XException.InvalidArgs.Throw(); + // } - // - var normalized = name.ToNormalString(); - var result = await scopes.FindOneAsync( - predicate: s => s.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 FindPolicyOrThrowAsync( - string name, - CancellationToken cancellationToken - ) - { - // - if (name.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } + // private async Task ValidateReferencesAsync( + // XPolicyDefinitionDto item, + // CancellationToken cancellationToken + // ) + // { + // // + // // Defensive guard ... + // if (item.IsNull()) + // { + // 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(); - } + // // + // // The DTO stores RequiredRoles / RequiredScopes as CSV strings. + // // Parse them into collections ONCE (ParseListString NREs on a null + // // string, so guard first) ... - // - return result; - } + // // + // var requiredRoles = item.RequiredRoles.IsNullOrEmpty() + // ? [] + // : item.RequiredRoles.ParseListString().ToList(); - private async Task ValidateReferencesAsync( - XPolicyDefinitionDto item, - CancellationToken cancellationToken - ) - { - // - // Defensive guard ... - if (item.IsNull()) - { - XException.InvalidArgs.Throw(); - } + // // + // var requiredScopes = item.RequiredScopes.IsNullOrEmpty() + // ? [] + // : item.RequiredScopes.ParseListString().ToList(); - // - // The DTO stores RequiredRoles / RequiredScopes as CSV strings. - // Parse them into collections ONCE (ParseListString NREs on a null - // string, so guard first) ... + // // + // // 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(); + // } + // } - // - var requiredRoles = item.RequiredRoles.IsNullOrEmpty() - ? [] - : item.RequiredRoles.ParseListString().ToList(); + // // + // // 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(); + // } + // } + // } - // - var requiredScopes = item.RequiredScopes.IsNullOrEmpty() - ? [] - : item.RequiredScopes.ParseListString().ToList(); + // private async Task ToDtoWithEffectiveRolesAsync( + // XPolicyDefinitionDto item, + // CancellationToken cancellationToken = default + // ) + // { + // // + // // Null / nameless guard ... + // if (item.IsNull() || item.Name.IsNullOrEmpty()) + // { + // return null; + // } - // - // 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(); - } - } + // // + // // 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(); - // - // 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(); - } - } - } + // // + // // Resolve the effective role set + // // (explicit RequiredRoles U roles by MinRoleWeight U parent chain) ... + // var effectiveRoles = await resolver.ResolveEffectiveRolesAsync( + // explicitRoles: explicitRoles, + // minRoleWeight: item.MinRoleWeight, + // cancellationToken: cancellationToken + // ); - private async Task ToDtoWithEffectiveRolesAsync( - XPolicyDefinitionDto item, - CancellationToken cancellationToken = default - ) - { - // - // Null / nameless guard ... - if (item.IsNull() || item.Name.IsNullOrEmpty()) - { - return null; - } + // // + // // Project onto XEffectiveAuthorizationDto - the ONLY DTO that carries + // // EffectiveRoles / EffectiveScopes / EffectiveClaims. Each CSV / JSON + // // field is null-guarded here (the shared ToEffectiveAuthorization + // // extension calls ParseListString on RequiredScopes without a null + // // guard, so the projection is built inline to stay null-safe) ... + // var result = new XEffectiveAuthorizationDto + // { + // PolicyName = item.Name, + // RequireEnabledUser = item.RequireEnabledUser, + // RequireAuthenticatedUser = item.RequireAuthenticatedUser, + // EffectiveClaims = item.RequiredClaims.ToRequiredClaims(), + // EffectiveScopes = item.RequiredScopes.IsNullOrEmpty() + // ? new HashSet(StringComparer.OrdinalIgnoreCase) + // : new HashSet( + // item.RequiredScopes.ParseListString(), + // StringComparer.OrdinalIgnoreCase + // ), + // EffectiveRoles = effectiveRoles.HasChild() + // ? new HashSet(effectiveRoles, StringComparer.OrdinalIgnoreCase) + // : new HashSet(StringComparer.OrdinalIgnoreCase), + // }; - // - // 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(); - - // - // Resolve the effective role set - // (explicit RequiredRoles U roles by MinRoleWeight U parent chain) ... - var effectiveRoles = await resolver.ResolveEffectiveRolesAsync( - explicitRoles: explicitRoles, - minRoleWeight: item.MinRoleWeight, - cancellationToken: cancellationToken - ); - - // - // Project onto XEffectiveAuthorizationDto - the ONLY DTO that carries - // EffectiveRoles / EffectiveScopes / EffectiveClaims. Each CSV / JSON - // field is null-guarded here (the shared ToEffectiveAuthorization - // extension calls ParseListString on RequiredScopes without a null - // guard, so the projection is built inline to stay null-safe) ... - var result = new XEffectiveAuthorizationDto - { - PolicyName = item.Name, - RequireEnabledUser = item.RequireEnabledUser, - RequireAuthenticatedUser = item.RequireAuthenticatedUser, - EffectiveClaims = item.RequiredClaims.ToRequiredClaims(), - EffectiveScopes = item.RequiredScopes.IsNullOrEmpty() - ? new HashSet(StringComparer.OrdinalIgnoreCase) - : new HashSet( - item.RequiredScopes.ParseListString(), - StringComparer.OrdinalIgnoreCase - ), - EffectiveRoles = effectiveRoles.HasChild() - ? new HashSet(effectiveRoles, StringComparer.OrdinalIgnoreCase) - : new HashSet(StringComparer.OrdinalIgnoreCase), - }; - - // - return result; - } - #endregion + // // + // return result; + // } + // #endregion } } \ No newline at end of file diff --git a/Providers/XDynamicPolicyProvider.cs b/Providers/XDynamicPolicyProvider.cs deleted file mode 100644 index c118fb4..0000000 --- a/Providers/XDynamicPolicyProvider.cs +++ /dev/null @@ -1,94 +0,0 @@ -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; - - public XDynamicPolicyProvider( - IXAuthorizationCache cache, - IServiceScopeFactory scopeFactory, - IOptions options - ) - { - // - this.cache = cache; - this.scopeFactory = scopeFactory; - fallback = new DefaultAuthorizationPolicyProvider(options); - } - - public Task GetDefaultPolicyAsync() => - fallback.GetDefaultPolicyAsync(); - - 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; - } - - // - // 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 - ); - - // - 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; - } - } - } - } - - // - // 3. Fallback to Static Policies (LocalApi.PolicyName, XPolicies.*) ... - return await fallback.GetPolicyAsync(policyName); - } - } -} \ No newline at end of file