+
Provider بهصورت partial (مثل XApplicationProvider) نوشته میشود. تنها قسمتهای وابسته به IdentityServer4/ASP.NET Identity پشت دو اینترفیس Sync پنهاناند تا ماژول netstandard2.0 بماند و پیادهسازی در xIds انجام شود (گام ۹).
+
+
Interfaces/IXScopeSyncService.cs + IXRoleSyncService.csusing System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+using xAuthorizationService.Models.Entities;
+
+namespace xAuthorizationService.Interfaces
+{
+ /// <summary>
+ /// Implemented on xIds over IdentityServer4 ConfigurationDbContext ...
+ /// </summary>
+ public interface IXScopeSyncService
+ {
+ Task UpsertAsync(XScopeDefinition scope, CancellationToken cancellationToken = default);
+ Task RemoveAsync(string scopeName, CancellationToken cancellationToken = default);
+ }
+
+ /// <summary>
+ /// Implemented on xIds over RoleManager<IdentityRole> ...
+ /// </summary>
+ public interface IXRoleSyncService
+ {
+ Task UpsertAsync(XRoleDefinition role, CancellationToken cancellationToken = default);
+ Task RemoveAsync(string roleName, CancellationToken cancellationToken = default);
+ Task<int> CountUsersInRoleAsync(string roleName, CancellationToken cancellationToken = default);
+ Task<IEnumerable<string>> GetUserRolesAsync(string userSelectByParam, CancellationToken cancellationToken = default);
+ }
+}
+
+
Interfaces/IXAuthorizationProvider.csusing xModels.Dtos;
+using System.Threading;
+using xIdentityModels.Models;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+using xAuthorizationService.Models.Dtos;
+
+namespace xAuthorizationService.Interfaces
+{
+ public interface IXAuthorizationProvider
+ {
+ //
+ #region Scope ...
+ Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync(XQuery query, CancellationToken cancellationToken = default);
+ Task<XScopeDefinitionDto> GetScopeAsync(string name, CancellationToken cancellationToken = default);
+ Task<XScopeDefinitionDto> AddScopeAsync(XScopeDefinitionDto item, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ Task<XScopeDefinitionDto> UpdateScopeAsync(string name, XScopeDefinitionDto item, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ Task<bool> RemoveScopeAsync(string name, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ #endregion
+
+ //
+ #region Role ...
+ Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(CancellationToken cancellationToken = default);
+ Task<XRoleDefinitionDto> GetRoleAsync(string name, CancellationToken cancellationToken = default);
+ Task<XRoleDefinitionDto> AddRoleAsync(XRoleDefinitionDto item, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ Task<XRoleDefinitionDto> UpdateRoleAsync(string name, XRoleDefinitionDto item, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ Task<bool> RemoveRoleAsync(string name, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ #endregion
+
+ //
+ #region Policy ...
+ Task<XQueryResult<XPolicyDefinitionDto>> QueryPoliciesAsync(XQuery query, CancellationToken cancellationToken = default);
+ Task<XPolicyDefinitionDto> GetPolicyAsync(string name, CancellationToken cancellationToken = default);
+ Task<XPolicyDefinitionDto> AddPolicyAsync(XPolicyDefinitionDto item, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ Task<XPolicyDefinitionDto> UpdatePolicyAsync(string name, XPolicyDefinitionDto item, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ Task<bool> RemovePolicyAsync(string name, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default);
+ Task<XPolicyEvaluationResultDto> EvaluatePolicyAsync(string name, XUserClaimsInfoDto target, CancellationToken cancellationToken = default);
+ #endregion
+
+ //
+ #region Utilities ...
+ Task SyncAllAsync(CancellationToken cancellationToken = default);
+ Task InvalidateAsync(string policyName = null);
+ #endregion
+ }
+}
+
Providers/XAuthorizationProvider.cs (Core — partial)using System;
+using xCommons.Extensions;
+using System.Threading.Tasks;
+using xEventService.Interfaces;
+using xAuthorizationService.Constants;
+using xAuthorizationService.Interfaces;
+using xAuthorizationService.Interfaces.Entities;
+
+namespace xAuthorizationService.Providers
+{
+ /// <summary>
+ /// a Service For Manage Scopes, Roles and Policies ...
+ /// </summary>
+ public partial class XAuthorizationProvider : IXAuthorizationProvider
+ {
+ private readonly IXAuthorizationCache cache;
+ private readonly IXRoleSyncService roleSync;
+ private readonly IXScopeSyncService scopeSync;
+ private readonly IXRoleHierarchyResolver resolver;
+ private readonly IXEventServiceProvider eventService;
+ private readonly IXRoleDefinitionRepositoryProvider roles;
+ private readonly IXScopeDefinitionRepositoryProvider scopes;
+ private readonly IXPolicyDefinitionRepositoryProvider policies;
+
+ public XAuthorizationProvider(
+ IXAuthorizationCache cache,
+ IXRoleHierarchyResolver resolver,
+ IXRoleDefinitionRepositoryProvider roles,
+ IXScopeDefinitionRepositoryProvider scopes,
+ IXPolicyDefinitionRepositoryProvider policies,
+ IXRoleSyncService roleSync = null,
+ IXScopeSyncService scopeSync = null,
+ IXEventServiceProvider eventService = null
+ )
+ {
+ //
+ this.cache = cache;
+ this.roles = roles;
+ this.scopes = scopes;
+ this.resolver = resolver;
+ this.policies = policies;
+ this.roleSync = roleSync;
+ this.scopeSync = scopeSync;
+ this.eventService = eventService;
+ }
+
+ /// <summary>
+ /// Clear Local Cache and Notify other Instances ...
+ /// </summary>
+ public async Task InvalidateAsync(string policyName = null)
+ {
+ //
+ if (policyName.IsNullOrEmpty())
+ {
+ cache.Clear();
+ }
+ else
+ {
+ cache.RemovePolicy(policyName);
+ }
+
+ //
+ // Publish authorization.changed (optional, when xEventService registered) ...
+ if (!eventService.IsNull())
+ {
+ //
+ try
+ {
+ await eventService.SendMessageAsync(
+ message: new xEventService.Models.XEventMessage
+ {
+ Action = XAuthorizationServiceConstants.AuthorizationChangedEvent,
+ Sender = nameof(XAuthorizationProvider),
+ Offset = DateTime.UtcNow,
+ Message = policyName ?? "*"
+ },
+ topic: XAuthorizationServiceConstants.AuthorizationChangedEvent
+ );
+ }
+ catch (Exception) { }
+ }
+ }
+ }
+}
+
Providers/XAuthorizationProvider+Policy.cs (الگو برای +Scope و +Role)using System;
+using System.Linq;
+using System.Threading;
+using xCommons.Extensions;
+using xExceptions.Constants;
+using xIdentityModels.Models;
+using System.Threading.Tasks;
+using xAuthorizationService.Models.Dtos;
+using xAuthorizationService.Extensions;
+using xAuthorizationService.Models.Entities;
+
+namespace xAuthorizationService.Providers
+{
+ public partial class XAuthorizationProvider
+ {
+ //
+ #region Policy ...
+ public async Task<XPolicyDefinitionDto> 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.Repository.FindOneAsync(
+ predicate: p => p.Name.ToLower() == normalized,
+ cancellationToken: cancellationToken
+ );
+ if (!exists.IsNull())
+ {
+ XException.Duplicate.Throw();
+ }
+
+ //
+ await ValidateReferencesAsync(item, cancellationToken);
+
+ //
+ var entity = item.ToEntity();
+ entity.IsSystem = false;
+
+ //
+ // XBaseEntityProvider.AddAsync → Repository + SignalR Push ...
+ var result = await policies.AddAsync(
+ item: entity,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ await InvalidateAsync(result.Name);
+
+ //
+ return await ToDtoWithEffectiveRolesAsync(result, cancellationToken);
+ }
+
+ public async Task<bool> 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 InvalidateAsync(entity.Name);
+ return true;
+ }
+
+ // GetPolicyAsync / QueryPoliciesAsync / UpdatePolicyAsync follow same style ...
+ #endregion
+
+ //
+ #region Private ...
+ private async Task<XPolicyDefinition> FindPolicyOrThrowAsync(
+ string name,
+ CancellationToken cancellationToken
+ )
+ {
+ //
+ if (name.IsNullOrEmpty())
+ {
+ XException.InvalidArgs.Throw();
+ }
+
+ //
+ var normalized = name.ToNormalString();
+ var result = await policies.Repository.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
+ )
+ {
+ //
+ // Referenced Roles must exist ...
+ if (item.RequiredRoles.HasChild())
+ {
+ var all = (await roles.Repository.GetAllAsync(cancellationToken: cancellationToken))
+ .Select(r => r.Name.ToNormalString()).ToList();
+ if (item.RequiredRoles.Any(r => !all.Contains(r.ToNormalString())))
+ {
+ XException.NotFound.Throw();
+ }
+ }
+
+ //
+ // Referenced Scopes must exist ...
+ if (item.RequiredScopes.HasChild())
+ {
+ var all = (await scopes.Repository.GetAllAsync(cancellationToken: cancellationToken))
+ .Select(s => s.Name.ToNormalString()).ToList();
+ if (item.RequiredScopes.Any(s => !all.Contains(s.ToNormalString())))
+ {
+ XException.NotFound.Throw();
+ }
+ }
+ }
+
+ private async Task<XPolicyDefinitionDto> ToDtoWithEffectiveRolesAsync(
+ XPolicyDefinition entity,
+ CancellationToken cancellationToken
+ )
+ {
+ //
+ var dto = entity.ToDto();
+ dto.EffectiveRoles = (await resolver.ResolveEffectiveRolesAsync(
+ explicitRoles: entity.RequiredRoles.ToCsvList(),
+ minRoleWeight: entity.MinRoleWeight,
+ cancellationToken: cancellationToken
+ )).ToList();
+
+ //
+ return dto;
+ }
+ #endregion
+ }
+}
+
Seeder — انتقال ثابتهای فعلی به DB با IsSystem = true
+
XBaseDbSeeder فریمورک از appsettings:XDataService.Databases[db].SeedItems[entity] میخواند. برای ثابتهای کد (که نباید در appsettings تکرار شوند) یک Seeder کدمحور مینویسیم که در UseXAuthorizationService پس از UseXRepository فراخوانی میشود (همان الگوی XDbSeeder.SeedData در xIds):
+
+
Providers/XAuthorizationSeeder.csusing System.Linq;
+using xIdentityHelper;
+using xCommons.Extensions;
+using xExceptions.Extensions;
+using System.Threading.Tasks;
+using xAuthorizationService.Constants;
+using xAuthorizationService.Models.Entities;
+using xAuthorizationService.Interfaces.Entities;
+using static xIdentityHelper.XApiScopeHelper;
+
+namespace xAuthorizationService.Providers
+{
+ /// <summary>
+ /// Seed System Scopes / Roles / Policies from xIdentityHelper constants ...
+ /// idempotent: only adds missing records by Name ...
+ /// </summary>
+ public class XAuthorizationSeeder
+ {
+ private readonly IXRoleDefinitionRepository roles;
+ private readonly IXScopeDefinitionRepository scopes;
+ private readonly IXPolicyDefinitionRepository policies;
+
+ public XAuthorizationSeeder(
+ IXRoleDefinitionRepository roles,
+ IXScopeDefinitionRepository scopes,
+ IXPolicyDefinitionRepository policies
+ )
+ {
+ this.roles = roles;
+ this.scopes = scopes;
+ this.policies = policies;
+ }
+
+ public async Task SeedAsync()
+ {
+ //
+ #region Scopes ...
+ var scopeNames = new[] { XApiScopes.Read, XApiScopes.Write, XApiScopes.Admin, XApiScopes.Manage };
+ foreach (var name in scopeNames)
+ {
+ //
+ var normalized = name.ToNormalString();
+ var exists = await scopes.FindOneAsync(s => s.Name.ToLower() == normalized);
+ if (exists.IsNull())
+ {
+ await scopes.AddAsync(new XScopeDefinition
+ {
+ Name = name,
+ DisplayName = name,
+ IsSystem = true,
+ IsEnabled = true
+ });
+ }
+ }
+ #endregion
+
+ //
+ #region Roles (Weight = XUserRole enum value) ...
+ foreach (XUserRole role in System.Enum.GetValues(typeof(XUserRole)))
+ {
+ //
+ var name = role.GetStringValue();
+ var normalized = name.ToNormalString();
+ var exists = await roles.FindOneAsync(r => r.Name.ToLower() == normalized);
+ if (exists.IsNull())
+ {
+ await roles.AddAsync(new XRoleDefinition
+ {
+ Name = name,
+ DisplayName = name,
+ Weight = (int)role,
+ IsSystem = true,
+ IsEnabled = true
+ });
+ }
+ }
+ #endregion
+
+ //
+ #region Policies (mirror of XAuthorizationHelper) ...
+ //
+ // Scope Policies ...
+ await SeedPolicyAsync(XPolicies.ReadAccess, XPolicyKind.ScopeBased, scopes: XApiScopes.Read, authenticated: false);
+ await SeedPolicyAsync(XPolicies.WriteAccess, XPolicyKind.ScopeBased, scopes: $"{XApiScopes.Read},{XApiScopes.Write}", authenticated: false);
+ await SeedPolicyAsync(XPolicies.AdminAccess, XPolicyKind.ScopeBased, scopes: $"{XApiScopes.Read},{XApiScopes.Write},{XApiScopes.Admin}", authenticated: false);
+ await SeedPolicyAsync(XPolicies.ManageAccess, XPolicyKind.ScopeBased, scopes: $"{XApiScopes.Read},{XApiScopes.Write},{XApiScopes.Admin},{XApiScopes.Manage}", authenticated: false);
+
+ //
+ // Role Policies: <Role> and Enabled<Role> with MinRoleWeight ...
+ await SeedRolePairAsync(XPolicies.User, XPolicies.EnabledUser, (int)XUserRole.User);
+ await SeedRolePairAsync(XPolicies.Agent, XPolicies.EnabledAgent, (int)XUserRole.Agent);
+ await SeedRolePairAsync(XPolicies.ReporterAssistant, XPolicies.EnabledReporterAssistant, (int)XUserRole.ReporterAssistant);
+ await SeedRolePairAsync(XPolicies.Reporter, XPolicies.EnabledReporter, (int)XUserRole.Reporter);
+ await SeedRolePairAsync(XPolicies.ActuaryAssistant, XPolicies.EnabledActuaryAssistant, (int)XUserRole.ActuaryAssistant);
+ await SeedRolePairAsync(XPolicies.Actuary, XPolicies.EnabledActuary, (int)XUserRole.Actuary);
+ await SeedRolePairAsync(XPolicies.ChiefClerkAssistant, XPolicies.EnabledChiefClerkAssistant, (int)XUserRole.ChiefClerkAssistant);
+ await SeedRolePairAsync(XPolicies.ChiefClerk, XPolicies.EnabledChiefClerk, (int)XUserRole.ChiefClerk);
+ await SeedRolePairAsync(XPolicies.Journalist, XPolicies.EnabledJournalist, (int)XUserRole.Journalist);
+ await SeedRolePairAsync(XPolicies.ResponsibleManager, XPolicies.EnabledResponsibleManager, (int)XUserRole.ResponsibleManager);
+ await SeedRolePairAsync(XPolicies.Admin, XPolicies.EnabledAdmin, (int)XUserRole.Admin);
+
+ //
+ // Complex: AdminOrAgent (explicit list, no weight) ...
+ await SeedPolicyAsync(XPolicies.AdminOrAgent, XPolicyKind.RoleBased, roles: $"{XUserRoles.ADMIN},{XUserRoles.AGENT}");
+ await SeedPolicyAsync(XPolicies.EnabledAdminOrAgent, XPolicyKind.RoleBased, roles: $"{XUserRoles.ADMIN},{XUserRoles.AGENT}", enabledUser: true);
+ #endregion
+ }
+
+ //
+ #region Private ...
+ private async Task SeedRolePairAsync(string policy, string enabledPolicy, int minWeight)
+ {
+ await SeedPolicyAsync(policy, XPolicyKind.RoleBased, minRoleWeight: minWeight);
+ await SeedPolicyAsync(enabledPolicy, XPolicyKind.RoleBased, minRoleWeight: minWeight, enabledUser: true);
+ }
+
+ private async Task SeedPolicyAsync(
+ string name,
+ XPolicyKind kind,
+ string roles = null,
+ string scopes = null,
+ int? minRoleWeight = null,
+ bool enabledUser = false,
+ bool authenticated = true
+ )
+ {
+ //
+ var normalized = name.ToNormalString();
+ var exists = await policies.FindOneAsync(p => p.Name.ToLower() == normalized);
+ if (!exists.IsNull())
+ {
+ return;
+ }
+
+ //
+ await policies.AddAsync(new XPolicyDefinition
+ {
+ Name = name,
+ DisplayName = name,
+ Kind = kind,
+ RequiredRoles = roles,
+ RequiredScopes = scopes,
+ MinRoleWeight = minRoleWeight,
+ RequireEnabledUser = enabledUser,
+ RequireAuthenticatedUser = authenticated,
+ IsSystem = true,
+ IsEnabled = true
+ });
+ }
+ #endregion
+ }
+}
+
+
DI/XDIHelperExtension.cs — افزودن به انتهای UseXAuthorizationService //
+ // Seed System Definitions (after Repositories are ready) ...
+ using (var scope = app.ApplicationServices.CreateScope())
+ {
+ //
+ var seeder = new XAuthorizationSeeder(
+ roles: scope.ServiceProvider.GetRequiredService<IXRoleDefinitionRepository>(),
+ scopes: scope.ServiceProvider.GetRequiredService<IXScopeDefinitionRepository>(),
+ policies: scope.ServiceProvider.GetRequiredService<IXPolicyDefinitionRepository>()
+ );
+
+ //
+ // same sync style as app.UseXIdentityServer → SeedData ...
+ seeder.SeedAsync().GetAwaiter().GetResult();
+ }
+
+
+ نتیجهی گام ۸: پس از اولین اجرا، DB شامل ۴ Scope، ۱۱ Role (با Weight) و ۳۰ Policy با IsSystem = true است که ۱:۱ با XAuthorizationHelper معادلاند. Seeder idempotent است و در اجراهای بعدی فقط رکوردهای غایب را اضافه میکند؛ بنابراین ویرایشهای ادمین روی رکوردهای موجود حفظ میشود.
+
+