From 384cffac36a67f3e6c85b2dcffa64cca8a37a1b5 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 26 Nov 2026 19:37:19 +0330 Subject: [PATCH] last ... --- Controllers/AccountController.cs | 5 +- Controllers/ApplicationsController.cs | 4 + .../AuthorizationController+Policy.cs | 12 + .../AuthorizationController+Role.cs | 59 ++++ .../AuthorizationController+Scope.cs | 12 + Controllers/AuthorizationController.cs | 38 +++ DI/XDIHelperExtension.cs | 5 +- Interfaces/IXIdentityManager.cs | 4 + Providers/XAuthorizationProvider.cs | 261 ++++++++++++++++++ .../XAuthorizationProvider+Role.cs | 181 ++++++++++++ .../XAuthorizationProvider+Scope.cs | 134 +++++++++ Providers/XDynamicPolicyProvider.cs | 99 +++++++ .../XIdentityManager/XIdentityManager+Role.cs | 50 ++++ Startup.cs | 24 +- 14 files changed, 882 insertions(+), 6 deletions(-) create mode 100644 Controllers/Authorization/AuthorizationController+Policy.cs create mode 100644 Controllers/Authorization/AuthorizationController+Role.cs create mode 100644 Controllers/Authorization/AuthorizationController+Scope.cs create mode 100644 Controllers/AuthorizationController.cs create mode 100644 Providers/XAuthorizationProvider.cs create mode 100644 Providers/XAuthorizationProvider/XAuthorizationProvider+Role.cs create mode 100644 Providers/XAuthorizationProvider/XAuthorizationProvider+Scope.cs create mode 100644 Providers/XDynamicPolicyProvider.cs diff --git a/Controllers/AccountController.cs b/Controllers/AccountController.cs index 12222c2..1b589ae 100644 --- a/Controllers/AccountController.cs +++ b/Controllers/AccountController.cs @@ -1,19 +1,22 @@ using xIds.Interfaces; using xCommons.Providers; +using xCommons.Attributes; using xIds.Controllers.Base; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; namespace xIds.Controllers { /// /// Provide all available tools for manipulating users and accounts /// + [Authorize] [ApiController] + [RequireXPowered] public partial class AccountController : XIBaseController { - public AccountController( IXIdentityManager identityManager, ILogger logger, diff --git a/Controllers/ApplicationsController.cs b/Controllers/ApplicationsController.cs index 6d8adc2..e88e41f 100644 --- a/Controllers/ApplicationsController.cs +++ b/Controllers/ApplicationsController.cs @@ -1,17 +1,21 @@ using xIds.Interfaces; using xCommons.Providers; using xIds.Configurations; +using xCommons.Attributes; using xIds.Controllers.Base; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; namespace xIds.Controllers { /// /// Provide all available tools for manipulating users and accounts /// + [Authorize] [ApiController] + [RequireXPowered] public partial class ApplicationsController : XIBaseController { private readonly IXApplicationProvider provider; diff --git a/Controllers/Authorization/AuthorizationController+Policy.cs b/Controllers/Authorization/AuthorizationController+Policy.cs new file mode 100644 index 0000000..1c526e2 --- /dev/null +++ b/Controllers/Authorization/AuthorizationController+Policy.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace xIds.Controllers +{ + public partial class AuthorizationController + { + + } +} \ No newline at end of file diff --git a/Controllers/Authorization/AuthorizationController+Role.cs b/Controllers/Authorization/AuthorizationController+Role.cs new file mode 100644 index 0000000..a6c3ba4 --- /dev/null +++ b/Controllers/Authorization/AuthorizationController+Role.cs @@ -0,0 +1,59 @@ +using System; +using xIdentityHelper; +using System.Threading; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +namespace xIds.Controllers +{ + public partial class AuthorizationController + { + /// + /// Retrieve Specified Role By Id ... + /// + /// + /// + /// + [HttpGet("Roles/{id}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public virtual async Task> Get( + [FromRoute] int id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!id.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + + // + var result = await roleProvider.GetAsync( + id: id, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + } +} \ No newline at end of file diff --git a/Controllers/Authorization/AuthorizationController+Scope.cs b/Controllers/Authorization/AuthorizationController+Scope.cs new file mode 100644 index 0000000..1c526e2 --- /dev/null +++ b/Controllers/Authorization/AuthorizationController+Scope.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace xIds.Controllers +{ + public partial class AuthorizationController + { + + } +} \ No newline at end of file diff --git a/Controllers/AuthorizationController.cs b/Controllers/AuthorizationController.cs new file mode 100644 index 0000000..233191b --- /dev/null +++ b/Controllers/AuthorizationController.cs @@ -0,0 +1,38 @@ +using xIds.Interfaces; +using xCommons.Providers; +using xCommons.Attributes; +using xIds.Controllers.Base; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xIds.Controllers +{ + [Authorize] + [ApiController] + [RequireXPowered] + public partial class AuthorizationController : XIBaseController + { + private readonly IXRoleProvider roleProvider; + private readonly IXScopeProvider scopeProvider; + private readonly IXPolicyProvider policyProvider; + + public AuthorizationController( + IXRoleProvider roleProvider, + IXScopeProvider scopeProvider, + IXPolicyProvider policyProvider, + IXIdentityManager identityManager, + XAppConfiguration appConfiguration, + XValidationProvider validationProvider, + ILogger logger + ) : base(logger, appConfiguration, identityManager, validationProvider) + { + // + this.roleProvider = roleProvider; + this.scopeProvider = scopeProvider; + this.policyProvider = policyProvider; + } + } +} \ No newline at end of file diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index 9dc37dc..2c19e6d 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -14,12 +14,12 @@ using xMessageService.DI; using xStorageService.DI; using xCommons.Extensions; using xIds.Configurations; +using xIdentityService.DI; using xExceptions.Constants; using xCommons.Authorization; using System.Collections.Generic; using xMessageService.Interfaces; using xStorageService.Interfaces; -using xIdentityModels.Interfaces; using xIdentityService.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; @@ -94,6 +94,9 @@ namespace xIds.DI source.AddScoped(); source.AddScoped(); source.AddScoped(); + + // + source.AddXAuthorizationProvider(); } /// diff --git a/Interfaces/IXIdentityManager.cs b/Interfaces/IXIdentityManager.cs index 9012331..c42a8ec 100644 --- a/Interfaces/IXIdentityManager.cs +++ b/Interfaces/IXIdentityManager.cs @@ -88,6 +88,10 @@ namespace xIds.Interfaces ); Task RemoveFromRoleAsync(XUser user, string roleName); Task RemoveFromRolesAsync(XUser user, IEnumerable roleNames); + Task DeleteRoleAsync( + string roleName, + CancellationToken cancellationToken = default + ); #endregion // diff --git a/Providers/XAuthorizationProvider.cs b/Providers/XAuthorizationProvider.cs new file mode 100644 index 0000000..9e522b6 --- /dev/null +++ b/Providers/XAuthorizationProvider.cs @@ -0,0 +1,261 @@ +using System; +using System.Linq; +using xIds.Interfaces; +using System.Threading; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xIdentityService.Models; +using System.Collections.Generic; +using IdentityServer4.Extensions; +using xIdentityService.Interfaces; +using xIdentityService.Extensions; + +namespace xIds.Providers +{ + public partial class XAuthorizationProvider : IXAuthorizationProvider + { + // + private readonly IXRoleProvider roles; + private readonly IXScopeProvider scopes; + private readonly IXIdentityManager manager; + private readonly IXPolicyProvider policies; + private readonly IXAuthorizationCache cache; + private readonly IXRoleHierarchyResolver resolver; + + public XAuthorizationProvider( + IXRoleProvider roles, + IXScopeProvider scopes, + IXIdentityManager manager, + IXPolicyProvider policies, + IXAuthorizationCache cache, + IXRoleHierarchyResolver resolver + ) + { + // + this.roles = roles; + this.cache = cache; + this.scopes = scopes; + this.manager = manager; + 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); + } + } + #endregion + + // + #region Private ... + private async Task FindRoleOrThrowAsync( + 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(); + } + + // + return result; + } + + private async Task FindScopeOrThrowAsync( + 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(); + } + + // + return result; + } + + 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(); + } + + // + return result; + } + + private async Task ValidateReferencesAsync( + XPolicyDefinitionDto item, + CancellationToken cancellationToken + ) + { + // + // Defensive guard ... + if (item.IsNull()) + { + XException.InvalidArgs.Throw(); + } + + // + // The DTO stores RequiredRoles / RequiredScopes as CSV strings. + // Parse them into collections ONCE (ParseListString NREs on a null + // string, so guard first) ... + + // + var requiredRoles = item.RequiredRoles.IsNullOrEmpty() + ? [] + : item.RequiredRoles.ParseListString().ToList(); + + // + var requiredScopes = item.RequiredScopes.IsNullOrEmpty() + ? [] + : item.RequiredScopes.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(); + } + } + + // + // 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 + ) + { + // + // Null / nameless guard ... + if (item.IsNull() || item.Name.IsNullOrEmpty()) + { + return null; + } + + // + // 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 + } +} \ No newline at end of file diff --git a/Providers/XAuthorizationProvider/XAuthorizationProvider+Role.cs b/Providers/XAuthorizationProvider/XAuthorizationProvider+Role.cs new file mode 100644 index 0000000..0d453d9 --- /dev/null +++ b/Providers/XAuthorizationProvider/XAuthorizationProvider+Role.cs @@ -0,0 +1,181 @@ +using System; +using System.Linq; +using System.Threading; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xIdentityModels.Models; + +namespace xIds.Providers +{ + public partial class XAuthorizationProvider + { + // + #region Role ... + public async Task AddRoleAsync( + XRoleDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (item.IsNull() || + item.Name.IsNullOrEmpty() || + userInfo.IsNullOrDefault() + ) + { + XException.InvalidArgs.Throw(); + } + + // + // Duplicate check via repository (NOT AsQueryable) ... + 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 locally first + item.IsSystem = false; + var result = await roles.AddAsync( + item: item, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + // Sync to IdentityServer — MUST check result + var identityResult = await manager.CreateRoleAsync(result.Name); + if (!identityResult.Succeeded) + { + // + // Rollback local insert to avoid permanent drift + await roles.RemoveAsync( + id: result.Id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + XException.ActionFailed.Throw(); + } + + // + await InvalidateAsync(); + return result; + } + + public async Task UpdateRoleAsync( + string name, + XRoleDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + if (name.IsNullOrEmpty() || item.IsNull()) + { + XException.InvalidArgs.Throw(); + } + + // + var existing = await FindRoleOrThrowAsync(name, cancellationToken); + if (existing.IsSystem) + { + XException.NotAllowed.Throw(); + } + + // + var updated = await roles.UpdateAsync( + item: item, + id: existing.Id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + // Sync to IdentityServer — rename requires delete+create in IdentityServer + if (!string.Equals( + existing.Name, + updated.Name, + StringComparison.OrdinalIgnoreCase) + ) + { + // + var usersInRole = await manager.UserManager + .GetUsersInRoleAsync(existing.Name.ToNormalString()); + + // + await manager.DeleteRoleAsync( + existing.Name, + cancellationToken + ); + + // + var identityResult = await manager.CreateRoleAsync(updated.Name); + if (!identityResult.Succeeded) + { + XException.ActionFailed.Throw(); + } + + // + foreach(var user in usersInRole) + { + // + await manager.AddUserToRoleAsync( + user: user, + roleName: updated.Name + ); + } + } + + // + await InvalidateAsync(); + return updated; + } + + public async Task RemoveRoleAsync( + string name, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + var existing = await FindRoleOrThrowAsync(name, cancellationToken); + if (existing.IsSystem) + { + XException.NotAllowed.Throw(); + } + + // + // ⚠️ CRITICAL: capture affected users BEFORE delete. + // After DeleteRoleAsync, AspNetUserRoles rows are gone. + var affectedUsers = await manager.UserManager.GetUsersInRoleAsync(existing.Name); + var affectedUserIds = affectedUsers.Select(u => u.Id).ToList(); + + // + // Delete from local DB + await roles.RemoveAsync( + id: existing.Id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + // Delete from IdentityServer — this cascades AspNetUserRoles + await manager.DeleteRoleAsync(existing.Name, cancellationToken); + + // + await InvalidateAsync(); + return true; + } + #endregion + } +} \ No newline at end of file diff --git a/Providers/XAuthorizationProvider/XAuthorizationProvider+Scope.cs b/Providers/XAuthorizationProvider/XAuthorizationProvider+Scope.cs new file mode 100644 index 0000000..856ac68 --- /dev/null +++ b/Providers/XAuthorizationProvider/XAuthorizationProvider+Scope.cs @@ -0,0 +1,134 @@ +using System; +using System.Linq; +using System.Threading; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xIdentityModels.Models; +using System.Collections.Generic; + +namespace xIds.Providers +{ + public partial class XAuthorizationProvider + { + // + #region Scope ... + public async Task> GetScopesAsync( + CancellationToken cancellationToken = default + ) + { + return await scopes + .GetAllAsync(cancellationToken: cancellationToken); + } + + public async Task GetScopeAsync( + string name, + CancellationToken cancellationToken = default + ) + { + return await FindScopeOrThrowAsync(name, cancellationToken); + } + + public async Task AddScopeAsync( + XScopeDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + if (item.IsNull() || item.Name.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var normalized = item.Name.ToNormalString(); + var exists = await scopes.FindOneAsync( + predicate: s => s.Name.ToLower() == normalized, + cancellationToken: cancellationToken); + if (!exists.IsNull()) + { + XException.Duplicate.Throw(); + } + + // + item.IsSystem = false; + var result = await scopes.AddAsync( + item: item, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + await InvalidateAsync(); + return result; + } + + public async Task UpdateScopeAsync( + string name, + XScopeDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + if (name.IsNullOrEmpty() || item.IsNull()) + { + XException.InvalidArgs.Throw(); + } + + // + var existing = await FindScopeOrThrowAsync(name, cancellationToken); + if (existing.IsSystem) + { + XException.NotAllowed.Throw(); + } + + // + var updated = await scopes.UpdateAsync( + item: item, + id: existing.Id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + await InvalidateAsync(); + return updated; + } + + public async Task RemoveScopeAsync( + string name, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + var existing = await FindScopeOrThrowAsync(name, cancellationToken); + if (existing.IsSystem) { + XException.NotAllowed.Throw(); + } + + // + var affectedPolicies = (await policies.GetAllAsync(cancellationToken: cancellationToken)) + .Where(p => !p.RequiredScopes.IsNullOrEmpty() + && p.RequiredScopes.ParseListString() + .Any(s => string.Equals(s, existing.Name, + StringComparison.OrdinalIgnoreCase))) + .ToList(); + + // + await scopes.RemoveAsync( + id: existing.Id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + await InvalidateAsync(); + return true; + } + #endregion + } +} \ No newline at end of file diff --git a/Providers/XDynamicPolicyProvider.cs b/Providers/XDynamicPolicyProvider.cs new file mode 100644 index 0000000..1c30e27 --- /dev/null +++ b/Providers/XDynamicPolicyProvider.cs @@ -0,0 +1,99 @@ +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 xIds.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); + } + + public Task GetFallbackPolicyAsync() + { + return Task.FromResult(null); + } + } +} \ No newline at end of file diff --git a/Providers/XIdentityManager/XIdentityManager+Role.cs b/Providers/XIdentityManager/XIdentityManager+Role.cs index deb765f..58d1c86 100644 --- a/Providers/XIdentityManager/XIdentityManager+Role.cs +++ b/Providers/XIdentityManager/XIdentityManager+Role.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using xCommons.Extensions; @@ -211,6 +212,55 @@ namespace xIds.Providers return result; } + /// + /// Delete a Role from Identity store (AspNetRoles) and cascade remove + /// all user assignments (AspNetUserRoles). + /// + /// role name + /// cancellation token (best-effort; Identity APIs are not cancellable) + /// an instance of IdentityResult + public async Task DeleteRoleAsync( + string roleName, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (roleName.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + // Honor cancellation at the entry point. RoleManager.DeleteAsync does not + // accept a CancellationToken, so this is a best-effort check before the call. + cancellationToken.ThrowIfCancellationRequested(); + + // + // Retrieve the role — throws XException.NotFound if it does not exist + var role = await GetRoleAsync(roleName); + + // + var usersInRole = await UserManager.GetUsersInRoleAsync(roleName); + foreach(var user in usersInRole) + { + // + await UserManager.RemoveFromRoleAsync( + user: user, + role: roleName + ); + } + + // + // Persist deletion. EF cascades to AspNetUserRoles automatically + // under the default Identity configuration (IdentityUserRole). + var result = await RoleManager.DeleteAsync(role); + + // + // Return Result ... + return result; + } + /// /// Check a User is Adminr not /// diff --git a/Startup.cs b/Startup.cs index 9b4a58b..053d294 100644 --- a/Startup.cs +++ b/Startup.cs @@ -80,12 +80,12 @@ namespace xIds // // Register Security Provider ... - services.AddSingleton(); + services.AddSingleton(); } public void Configure( - IApplicationBuilder app, - IWebHostEnvironment env, + IApplicationBuilder app, + IWebHostEnvironment env, ILogger logger ) { @@ -133,7 +133,23 @@ namespace xIds // app.UseEndpoints(endpoints => { - endpoints.MapDefaultControllerRoute(); + // + // endpoints.MapDefaultControllerRoute(); + + // + try + { + endpoints.MapDefaultControllerRoute(); + } + catch (ReflectionTypeLoadException ex) + { + foreach (var loaderException in ex.LoaderExceptions) + { + // Log or inspect the specific error, e.g., "Could not load file or assembly..." + Console.WriteLine(loaderException?.Message); + } + throw; // Re-throw to preserve the original behavior + } }); } }