diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index 26d0489..0f055ac 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -13,6 +13,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using IdentityModel.AspNetCore.OAuth2Introspection; using xHttpService.Interfaces; +using xExceptions.Constants; namespace xIdentityService.DI { @@ -123,6 +124,22 @@ namespace xIdentityService.DI { source.AddSingleton(); } + + public static void AddXRoleHierarchyResolver( + this IServiceCollection source + ) + { + // + // Check Provider ... + var providerService = source.GetRegisteredService(); + if (providerService.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + source.AddScoped(); + } /// /// Use Authentication diff --git a/Extensions/XPolicyDefinitionExtensions.cs b/Extensions/XPolicyDefinitionExtensions.cs index b0cb4e0..13983fa 100644 --- a/Extensions/XPolicyDefinitionExtensions.cs +++ b/Extensions/XPolicyDefinitionExtensions.cs @@ -1,10 +1,11 @@ -using System; using System.Linq; using IdentityModel; using xCommons.Constants; using xCommons.Extensions; +using xIdentityModels.Dtos; using xIdentityModels.Models; using xCommons.Authorization; +using xIdentityService.Models; using System.Collections.Generic; using Microsoft.AspNetCore.Authorization; @@ -12,73 +13,41 @@ namespace xIdentityService.Extensions { public static class XPolicyDefinitionExtensions { - /// - /// Split Comma Separated Values (same style as XTag.References) ... - /// - /// - /// - // public static List ToCsvList(this string source) - // { - // // - // if (source.IsNullOrEmpty()) - // { - // return []; - // } - - // // - // return source - // .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) - // .Select(s => s.Trim()) - // .Where(s => !s.IsNullOrEmpty()) - // .Distinct() - // .ToList(); - // } - - /// - /// Join Values as Comma Separated String ... - /// - /// - /// - // public static string ToCsv(this IEnumerable source) - // { - // // - // if (!source.HasChild()) - // { - // return null; - // } - - // // - // return string.Join(",", source - // .Where(s => !s.IsNullOrEmpty()) - // .Select(s => s.Trim()) - // .Distinct()); - // } - /// /// Deserialize Json Array of Required Claims ... /// /// /// - // public static List ToRequiredClaims(this string json) - // { - // } + public static List ToRequiredClaims(this string json) + { + // + var result = new List(); - /// - /// Serialize Required Claims to Json ... - /// - /// - /// - // public static string ToRequiredClaimsJson(this IEnumerable source) - // { - // // - // if (!source.HasChild()) - // { - // return null; - // } + // + // Validate ... + if (json.IsNullOrEmpty()) + { + return result; + } - // // - // return JsonConvert.SerializeObject(source); - // } + // + try + { + // + result = json.FromJSON>(); + } + catch + { } + + // + if (result.IsNull()) + { + result = []; + } + + // + return result; + } /// /// Build AuthorizationPolicy exactly like XAuthorizationHelper does ... @@ -86,91 +55,184 @@ namespace xIdentityService.Extensions /// /// already resolved by IXRoleHierarchyResolver /// - // public static AuthorizationPolicy ToAuthorizationPolicy( - // this XPolicyDefinition source, - // IEnumerable effectiveRoles - // ) - // { - // // - // if (source.IsNull() || source.Name.IsNullOrEmpty()) - // { - // return null; - // } + public static AuthorizationPolicy ToAuthorizationPolicy( + this XPolicyDefinition source, + IEnumerable effectiveRoles + ) + { + // + if (source.IsNull() || source.Name.IsNullOrEmpty()) + { + return null; + } - // // - // var builder = new AuthorizationPolicyBuilder(); + // + var builder = new AuthorizationPolicyBuilder(); - // // - // // Authenticated User ... - // if (source.RequireAuthenticatedUser) - // { - // builder.RequireAuthenticatedUser(); - // } + // + // Authenticated User ... + if (source.RequireAuthenticatedUser) + { + builder.RequireAuthenticatedUser(); + } - // // - // // Roles (RequiredRolesRequirement, handled by RequiredRolesHandler) ... - // if (effectiveRoles.HasChild()) - // { - // builder.AddRequirements(new RequiredRolesRequirement(effectiveRoles.ToArray())); - // } + // + // Roles (RequiredRolesRequirement, handled by RequiredRolesHandler) ... + if (effectiveRoles.HasChild()) + { + builder.AddRequirements(new RequiredRolesRequirement(effectiveRoles.ToArray())); + } - // // - // // Scopes ... - // var scopes = source.RequiredScopes.ToCsvList(); - // if (scopes.HasChild()) - // { - // builder.RequireClaim(JwtClaimTypes.Scope, scopes.ToArray()); - // } + // + // Scopes ... + var scopes = source.RequiredScopes.ParseListString(); + if (scopes.HasChild()) + { + builder.RequireClaim(JwtClaimTypes.Scope, [.. scopes]); + } - // // - // // Custom Claims ... - // foreach (var claim in source.RequiredClaims.ToRequiredClaims()) - // { - // // - // if (claim.Type.IsNullOrEmpty()) - // { - // continue; - // } + // + // Custom Claims ... + foreach (var claim in source.RequiredClaims.ToRequiredClaims()) + { + // + if (claim.Type.IsNullOrEmpty()) + { + continue; + } - // // - // if (claim.Values.HasChild()) - // { - // builder.RequireClaim(claim.Type, claim.Values.ToArray()); - // } - // else - // { - // builder.RequireClaim(claim.Type); - // } - // } + // + if (claim.Values.HasChild()) + { + builder.RequireClaim(claim.Type, claim.Values.ToArray()); + } + else + { + builder.RequireClaim(claim.Type); + } + } - // // - // // Enabled User (IsBanned=false & IsEnabled=true) ... - // if (source.RequireEnabledUser) - // { - // // - // builder.RequireClaim( - // XCustomClaims.IsBanned, - // false.ToString(), - // false.ToString().ToNormalString() - // ); + // + // Enabled User (IsBanned=false & IsEnabled=true) ... + if (source.RequireEnabledUser) + { + // + builder.RequireClaim( + XCustomClaims.IsBanned, + false.ToString(), + false.ToString().ToNormalString() + ); - // // - // builder.RequireClaim( - // XCustomClaims.IsEnabled, - // true.ToString(), - // true.ToString().ToNormalString() - // ); - // } + // + builder.RequireClaim( + XCustomClaims.IsEnabled, + true.ToString(), + true.ToString().ToNormalString() + ); + } - // // - // // Nothing Required => at least Deny Anonymous to avoid an Empty Policy ... - // if (!builder.Requirements.HasChild()) - // { - // builder.RequireAuthenticatedUser(); - // } + // + // Nothing Required => at least Deny Anonymous to avoid an Empty Policy ... + if (!builder.Requirements.HasChild()) + { + builder.RequireAuthenticatedUser(); + } - // // - // return builder.Build(); - // } + // + return builder.Build(); + } + + /// + /// Build AuthorizationPolicy exactly like XAuthorizationHelper does ... + /// + /// + /// already resolved by IXRoleHierarchyResolver + /// + public static AuthorizationPolicy ToAuthorizationPolicy( + this XPolicyDefinitionDto source, + IEnumerable effectiveRoles + ) + { + // + if (source.IsNull() || source.Name.IsNullOrEmpty()) + { + return null; + } + + // + var builder = new AuthorizationPolicyBuilder(); + + // + // Authenticated User ... + if (source.RequireAuthenticatedUser) + { + builder.RequireAuthenticatedUser(); + } + + // + // Roles (RequiredRolesRequirement, handled by RequiredRolesHandler) ... + if (effectiveRoles.HasChild()) + { + builder.AddRequirements(new RequiredRolesRequirement(effectiveRoles.ToArray())); + } + + // + // Scopes ... + var scopes = source.RequiredScopes.ParseListString(); + if (scopes.HasChild()) + { + builder.RequireClaim(JwtClaimTypes.Scope, [.. scopes]); + } + + // + // Custom Claims ... + foreach (var claim in source.RequiredClaims.ToRequiredClaims()) + { + // + if (claim.Type.IsNullOrEmpty()) + { + continue; + } + + // + if (claim.Values.HasChild()) + { + builder.RequireClaim(claim.Type, claim.Values.ToArray()); + } + else + { + builder.RequireClaim(claim.Type); + } + } + + // + // Enabled User (IsBanned=false & IsEnabled=true) ... + if (source.RequireEnabledUser) + { + // + builder.RequireClaim( + XCustomClaims.IsBanned, + false.ToString(), + false.ToString().ToNormalString() + ); + + // + builder.RequireClaim( + XCustomClaims.IsEnabled, + true.ToString(), + true.ToString().ToNormalString() + ); + } + + // + // Nothing Required => at least Deny Anonymous to avoid an Empty Policy ... + if (!builder.Requirements.HasChild()) + { + builder.RequireAuthenticatedUser(); + } + + // + return builder.Build(); + } } } \ No newline at end of file diff --git a/Interfaces/IXAuthorizationProvider.cs b/Interfaces/IXAuthorizationProvider.cs new file mode 100644 index 0000000..99009e6 --- /dev/null +++ b/Interfaces/IXAuthorizationProvider.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using xIdentityModels.Dtos; +using xIdentityModels.Models; +using xModels.Dtos; + +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 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 diff --git a/Interfaces/IXRoleHierarchyResolver.cs b/Interfaces/IXRoleHierarchyResolver.cs new file mode 100644 index 0000000..836750c --- /dev/null +++ b/Interfaces/IXRoleHierarchyResolver.cs @@ -0,0 +1,34 @@ +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace xIdentityService.Interfaces +{ + public interface IXRoleHierarchyResolver + { + /// + /// Retrieve All Enabled Role Names which Weight >= minWeight ... + /// + /// + /// + /// + Task> GetRolesByMinWeightAsync( + int minWeight, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve Effective Roles for a Policy + /// (explicit RequiredRoles ∪ roles by MinRoleWeight ∪ parents chain) ... + /// + /// + /// + /// + /// + Task> ResolveEffectiveRolesAsync( + IEnumerable explicitRoles, + int? minRoleWeight, + CancellationToken cancellationToken = default + ); + } +} \ No newline at end of file diff --git a/Interfaces/IXSyncService.cs b/Interfaces/IXSyncService.cs new file mode 100644 index 0000000..1442218 --- /dev/null +++ b/Interfaces/IXSyncService.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace xIdentityService.Interfaces +{ + public interface IXScopeSyncService + { + /// + /// 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/Models/XPolicyEvaluationResultDto.cs b/Models/XPolicyEvaluationResultDto.cs new file mode 100644 index 0000000..982dc1f --- /dev/null +++ b/Models/XPolicyEvaluationResultDto.cs @@ -0,0 +1,9 @@ +namespace xIdentityService.Models +{ + public class XPolicyEvaluationResultDto + { + public bool Passed { get; set; } + public string Policy { get; set; } + public List FailedRequirements { get; set; } = new List(); + } +} \ No newline at end of file diff --git a/Models/XRequiredClaimDto.cs b/Models/XRequiredClaimDto.cs new file mode 100644 index 0000000..ca9df0f --- /dev/null +++ b/Models/XRequiredClaimDto.cs @@ -0,0 +1,8 @@ +namespace xIdentityService.Models +{ + public class XRequiredClaimDto + { + public string Type { get; set; } + public List Values { get; set; } + } +} \ No newline at end of file diff --git a/Providers/XAuthorizationProvider.cs b/Providers/XAuthorizationProvider.cs new file mode 100644 index 0000000..7d45e39 --- /dev/null +++ b/Providers/XAuthorizationProvider.cs @@ -0,0 +1,9 @@ +using xIdentityService.Interfaces; + +namespace xIdentityService.Providers +{ + public class XAuthorizationProvider : IXAuthorizationProvider + { + + } +} \ No newline at end of file diff --git a/Providers/XDynamicPolicyProvider.cs b/Providers/XDynamicPolicyProvider.cs new file mode 100644 index 0000000..c118fb4 --- /dev/null +++ b/Providers/XDynamicPolicyProvider.cs @@ -0,0 +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; + +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 diff --git a/Providers/XRoleHierarchyResolver.cs b/Providers/XRoleHierarchyResolver.cs new file mode 100644 index 0000000..081eb58 --- /dev/null +++ b/Providers/XRoleHierarchyResolver.cs @@ -0,0 +1,100 @@ +using System; +using System.Linq; +using System.Threading; +using xCommons.Extensions; +using System.Threading.Tasks; +using System.Collections.Generic; +using xIdentityService.Interfaces; + +namespace xIdentityService.Providers +{ + public class XRoleHierarchyResolver : IXRoleHierarchyResolver + { + private readonly IXRoleProvider provider; + + public XRoleHierarchyResolver( + IXRoleProvider provider + ) + { + this.provider = provider; + } + + public async Task> GetRolesByMinWeightAsync( + int minWeight, + CancellationToken cancellationToken = default + ) + { + // + var roles = await provider.FindManyAsync( + predicate: r => r.IsEnabled && r.Weight >= minWeight, + orderBuilder: q => q.OrderBy(r => r.Weight), + cancellationToken: cancellationToken + ); + + // + var result = roles + .Select(r => r.Name.ToNormalString()) + .Distinct() + .ToList(); + return result; + } + + public async Task> ResolveEffectiveRolesAsync( + IEnumerable explicitRoles, + int? minRoleWeight, + CancellationToken cancellationToken = default + ) + { + // + var result = new HashSet(StringComparer.InvariantCultureIgnoreCase); + + // + // Explicit Roles ... + if (explicitRoles.HasChild()) + { + // + foreach (var role in explicitRoles) + { + result.Add(role.ToNormalString()); + } + } + + // + // Roles by Weight ... + if (minRoleWeight.HasValue) + { + // + var byWeight = await GetRolesByMinWeightAsync( + minRoleWeight.Value, + cancellationToken + ); + foreach (var role in byWeight) + { + result.Add(role); + } + } + + // + // Parent Chain: any Role whose ParentRoleName is in result inherits it ... + var all = await provider.GetAllAsync(cancellationToken: cancellationToken); + bool changed; + do + { + // + changed = false; + foreach (var role in all.Where(r => r.IsEnabled && !r.ParentRoleName.IsNullOrEmpty())) + { + // + if (result.Contains(role.ParentRoleName) && + result.Add(role.Name.ToNormalString())) + { + changed = true; + } + } + } while (changed); + + // + return [.. result]; + } + } +} \ No newline at end of file