3205 lines
142 KiB
HTML
3205 lines
142 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="fa" dir="rtl">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>راهنمای گامبهگام پیادهسازی xAuthorizationService | 1405-08-23</title>
|
||
<style>
|
||
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
|
||
|
||
:root {
|
||
--primary: #1a365d;
|
||
--primary-light: #2c5282;
|
||
--accent: #c9a961;
|
||
--accent-dark: #a8893f;
|
||
--bg: #faf9f6;
|
||
--card-bg: #ffffff;
|
||
--text: #1a202c;
|
||
--text-muted: #4a5568;
|
||
--border: #e2e8f0;
|
||
--success: #38a169;
|
||
--danger: #e53e3e;
|
||
--warning: #dd6b20;
|
||
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
|
||
}
|
||
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
|
||
body {
|
||
font-family: 'Vazirmatn', Tahoma, sans-serif;
|
||
background: var(--bg);
|
||
color: var(--text);
|
||
line-height: 1.9;
|
||
font-size: 15px;
|
||
padding: 30px 15px;
|
||
}
|
||
|
||
.document-container {
|
||
max-width: 950px;
|
||
margin: 0 auto;
|
||
background: var(--card-bg);
|
||
box-shadow: var(--shadow);
|
||
border-radius: 12px;
|
||
overflow: hidden;
|
||
}
|
||
|
||
.document-header {
|
||
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
|
||
color: white;
|
||
padding: 50px 40px 40px;
|
||
position: relative;
|
||
border-bottom: 4px solid var(--accent);
|
||
}
|
||
|
||
.document-header::before {
|
||
content: '';
|
||
position: absolute;
|
||
top: 0; right: 0;
|
||
width: 200px; height: 200px;
|
||
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
|
||
border-radius: 50%;
|
||
transform: translate(50%, -50%);
|
||
}
|
||
|
||
.header-top {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
margin-bottom: 30px;
|
||
position: relative;
|
||
z-index: 1;
|
||
}
|
||
|
||
.company-badge { display: flex; align-items: center; gap: 12px; }
|
||
|
||
.company-logo {
|
||
width: 60px; height: 60px;
|
||
background: var(--accent);
|
||
border-radius: 12px;
|
||
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
|
||
}
|
||
|
||
.doc-meta { text-align: left; font-size: 12px; opacity: 0.9; }
|
||
.doc-meta div { margin-bottom: 3px; }
|
||
|
||
.document-title { text-align: center; position: relative; z-index: 1; padding: 20px 0; }
|
||
|
||
.document-title .label {
|
||
display: inline-block;
|
||
background: rgba(201,169,97,0.2);
|
||
color: var(--accent);
|
||
padding: 4px 16px;
|
||
border-radius: 20px;
|
||
font-size: 12px;
|
||
font-weight: 600;
|
||
margin-bottom: 15px;
|
||
border: 1px solid rgba(201,169,97,0.4);
|
||
}
|
||
|
||
.document-title h1 { font-size: 28px; font-weight: 800; margin-bottom: 10px; letter-spacing: -0.5px; }
|
||
.document-title h2 { font-size: 16px; font-weight: 400; opacity: 0.9; }
|
||
|
||
.document-body { padding: 40px; }
|
||
|
||
.intro-text {
|
||
background: linear-gradient(to left, #f7fafc, #edf2f7);
|
||
border-right: 4px solid var(--accent);
|
||
padding: 20px 25px;
|
||
border-radius: 8px;
|
||
margin-bottom: 35px;
|
||
font-size: 14px;
|
||
color: var(--text-muted);
|
||
}
|
||
|
||
.section { margin-bottom: 40px; page-break-inside: avoid; }
|
||
|
||
.section-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 15px;
|
||
padding-bottom: 12px;
|
||
border-bottom: 2px solid var(--border);
|
||
margin-bottom: 20px;
|
||
}
|
||
|
||
.section-number {
|
||
width: 50px; height: 50px;
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
border-radius: 12px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-weight: 800;
|
||
font-size: 20px;
|
||
flex-shrink: 0;
|
||
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
|
||
}
|
||
|
||
.section-title { flex: 1; }
|
||
.section-title h3 { font-size: 19px; font-weight: 700; color: var(--primary); margin-bottom: 2px; }
|
||
.section-title .subtitle { font-size: 12px; color: var(--text-muted); }
|
||
|
||
.section-content { padding-right: 10px; }
|
||
.section-content p { margin-bottom: 12px; text-align: justify; text-indent: 20px; }
|
||
.section-content p.no-indent { text-indent: 0; }
|
||
.section-content h4 { color: var(--primary); margin: 18px 0 10px; font-size: 15px; }
|
||
.section-content ul.plain { margin: 8px 25px 12px 0; }
|
||
.section-content ul.plain li { margin-bottom: 4px; }
|
||
|
||
.highlight-box {
|
||
background: linear-gradient(to left, #fffaf0, #fef5e7);
|
||
border: 1px solid #f6e05e;
|
||
border-right: 4px solid var(--accent);
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
font-size: 14px;
|
||
}
|
||
.highlight-box strong { color: var(--accent-dark); }
|
||
|
||
.info-box {
|
||
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
|
||
border: 1px solid #90cdf4;
|
||
border-right: 4px solid var(--primary-light);
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
font-size: 14px;
|
||
}
|
||
|
||
.success-box {
|
||
background: linear-gradient(to left, #f0fff4, #e6fffa);
|
||
border: 1px solid #9ae6b4;
|
||
border-right: 4px solid var(--success);
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
font-size: 14px;
|
||
}
|
||
|
||
.warning-box {
|
||
background: linear-gradient(to left, #fffaf0, #fef5e7);
|
||
border: 1px solid #fbd38d;
|
||
border-right: 4px solid var(--warning);
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
font-size: 14px;
|
||
}
|
||
.styled-table { width: 100%; border-collapse: collapse; margin: 20px 0; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
|
||
.styled-table thead { background: linear-gradient(135deg, var(--primary), var(--primary-light)); color: white; }
|
||
.styled-table th { padding: 14px 16px; text-align: right; font-weight: 600; font-size: 13px; }
|
||
.styled-table td { padding: 13px 16px; border-bottom: 1px solid var(--border); font-size: 13px; }
|
||
.styled-table tbody tr:last-child td { border-bottom: none; }
|
||
.styled-table tbody tr:nth-child(even) { background: #f8fafc; }
|
||
.styled-table .highlight-row { background: #fffaf0 !important; font-weight: 600; }
|
||
|
||
.comparison-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 25px 0; }
|
||
.comparison-card { background: #f8fafc; border: 2px solid var(--border); border-radius: 10px; padding: 20px; position: relative; }
|
||
.comparison-card.recommended { border-color: var(--success); background: linear-gradient(to left, #f0fff4, #e6fffa); }
|
||
.comparison-card .card-badge { position: absolute; top: -10px; right: 20px; background: var(--success); color: white; padding: 3px 12px; border-radius: 15px; font-size: 11px; font-weight: 600; }
|
||
.comparison-card h4 { font-size: 16px; font-weight: 700; color: var(--primary); margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid var(--border); }
|
||
.comparison-card.recommended h4 { border-bottom-color: var(--success); }
|
||
.comparison-card ul { list-style: none; padding: 0; }
|
||
.comparison-card ul li { padding: 8px 0; border-bottom: 1px solid var(--border); font-size: 13px; display: flex; justify-content: space-between; }
|
||
.comparison-card ul li:last-child { border-bottom: none; }
|
||
.comparison-card ul li .value { font-weight: 600; color: var(--primary); }
|
||
|
||
.quote-box { background: linear-gradient(135deg, #f7fafc, #edf2f7); border-right: 4px solid var(--accent); padding: 20px 25px; border-radius: 8px; margin: 20px 0; position: relative; }
|
||
.quote-box p { font-style: italic; color: var(--text-muted); margin-bottom: 10px; text-indent: 0 !important; }
|
||
|
||
.code-box { direction: ltr; text-align: left; background: #1a202c; color: #e2e8f0; border-radius: 8px; border-left: 4px solid var(--accent); padding: 16px 20px; margin: 15px 0 20px; font-family: Consolas, 'Courier New', monospace; font-size: 12px; line-height: 1.6; overflow-x: auto; }
|
||
.code-box pre { margin: 0; white-space: pre; }
|
||
.code-box .file { display: block; color: var(--accent); font-weight: 700; margin-bottom: 8px; padding-bottom: 6px; border-bottom: 1px dashed rgba(201,169,97,0.4); }
|
||
|
||
.stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin: 25px 0; }
|
||
.stat-card { background: linear-gradient(135deg, var(--primary), var(--primary-light)); color: white; padding: 20px; border-radius: 10px; text-align: center; box-shadow: 0 4px 12px rgba(26,54,93,0.2); }
|
||
.stat-card .stat-value { font-size: 24px; font-weight: 800; margin-bottom: 5px; color: var(--accent); line-height: 1.3; }
|
||
.stat-card .stat-label { font-size: 12px; opacity: 0.9; }
|
||
.timeline { position: relative; padding: 20px 0; margin: 25px 0; }
|
||
.timeline::before { content: ''; position: absolute; right: 50%; top: 0; bottom: 0; width: 3px; background: var(--border); transform: translateX(50%); }
|
||
.timeline-item { display: flex; margin-bottom: 20px; position: relative; }
|
||
.timeline-item:nth-child(odd) { flex-direction: row-reverse; }
|
||
.timeline-content { width: 45%; background: #f8fafc; border: 1px solid var(--border); border-radius: 8px; padding: 15px; position: relative; }
|
||
.timeline-item:nth-child(odd) .timeline-content { margin-left: 5%; }
|
||
.timeline-item:nth-child(even) .timeline-content { margin-right: 5%; }
|
||
.timeline-dot { position: absolute; right: 50%; top: 20px; width: 16px; height: 16px; background: var(--accent); border: 3px solid white; border-radius: 50%; transform: translateX(50%); box-shadow: 0 2px 6px rgba(0,0,0,0.2); z-index: 1; }
|
||
.timeline-content h5 { font-size: 14px; font-weight: 700; color: var(--primary); margin-bottom: 8px; }
|
||
.timeline-content p { font-size: 12px; color: var(--text-muted); text-indent: 0 !important; margin-bottom: 0 !important; }
|
||
|
||
.reference-list { list-style: none; padding: 0; margin: 20px 0; }
|
||
.reference-list li { background: #f8fafc; border-right: 3px solid var(--primary-light); padding: 15px 20px; margin-bottom: 10px; border-radius: 6px; font-size: 13px; }
|
||
.reference-list li strong { color: var(--primary); display: block; margin-bottom: 5px; }
|
||
|
||
.conclusion-box { background: linear-gradient(135deg, var(--primary), var(--primary-light)); color: white; padding: 30px; border-radius: 12px; margin: 30px 0; text-align: center; box-shadow: 0 8px 20px rgba(26,54,93,0.3); }
|
||
.conclusion-box h3 { font-size: 22px; font-weight: 800; margin-bottom: 15px; color: var(--accent); }
|
||
.conclusion-box p { font-size: 14px; line-height: 1.8; text-indent: 0 !important; margin-bottom: 15px; }
|
||
.conclusion-box .highlight { background: rgba(201,169,97,0.2); padding: 15px 20px; border-radius: 8px; margin-top: 20px; border: 1px solid rgba(201,169,97,0.4); }
|
||
|
||
.document-footer { background: var(--primary); color: white; padding: 25px 40px; text-align: center; font-size: 12px; margin-top: 40px; }
|
||
.document-footer .footer-brand { font-weight: 700; color: var(--accent); margin-bottom: 5px; font-size: 14px; }
|
||
.footer-divider { width: 60px; height: 2px; background: var(--accent); margin: 10px auto; }
|
||
.page-info { text-align: center; padding: 15px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 30px; }
|
||
|
||
@media print { body { background: white; padding: 0; } .document-container { box-shadow: none; border-radius: 0; } .section { page-break-inside: avoid; } }
|
||
@media (max-width: 768px) { .document-body { padding: 25px 20px; } .document-header { padding: 30px 20px; } .comparison-grid { grid-template-columns: 1fr; } .stats-grid { grid-template-columns: 1fr; } .header-top { flex-direction: column; gap: 15px; } .doc-meta { text-align: center; } }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<div class="document-container">
|
||
|
||
<header class="document-header">
|
||
<div class="header-top">
|
||
<div class="company-badge">
|
||
<div class="company-logo"></div>
|
||
</div>
|
||
<div class="doc-meta">
|
||
<div>شماره مستند: ARCH-1405-0823-3</div>
|
||
<div>نسخه: ۳.۰</div>
|
||
<div>تاریخ تهیه: ۲۳ آبان ۱۴۰۵</div>
|
||
<div>طبقهبندی: داخلی / فنی</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="document-title">
|
||
<span class="label">IMPLEMENTATION GUIDE — xAuthorizationService</span>
|
||
<h1>راهنمای گامبهگام پیادهسازی ماژول xAuthorizationService</h1>
|
||
<h2>مدیریت پویای Scope / Role / Policy بر پایهی xIds، xIdentityModels و xIdentityService</h2>
|
||
</div>
|
||
</header>
|
||
|
||
<div class="document-body">
|
||
|
||
<div class="intro-text">
|
||
<strong>هدف مستند:</strong><br>
|
||
این مستند ادامهی مستند <code>1405-08-23_Overview_v.2</code> است. در نسخهی قبل، معماری فعلی هویت تحلیل و طرح کلی سرویس مدیریت پویای مجوزها ارائه شد. در این نسخه، <strong>دستورالعمل اجرایی و گامبهگام</strong> ساخت ماژول <code>Modules/xAuthorizationService</code> و یکپارچهسازی آن با <code>xIds</code> و <code>xIdentityService</code> ارائه میشود. تمام نمونهکدها دقیقاً مطابق Blueprint فعلی فریمورک (الگوی <code>xTagService</code>: Entity / Dto / KeyGenerator / RepositoryEvents / EF-Mongo-InMemory Repository / EntityHub / GraphQL / Helper Descriptor / <code>XDIHelperExtension</code>) و دستخط کد موجود (کامنت <code>//</code> در ابتدای هر بلوک، <code>#region</code>، <code>XException.X.Throw()</code>، <code>IsNull()/IsNullOrEmpty()/HasChild()</code>، usingهای مرتب بر اساس طول) نوشته شدهاند.
|
||
</div>
|
||
<!-- ===================== بخش ۱ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۱</div>
|
||
<div class="section-title">
|
||
<h3>خلاصهی وضعیت فعلی، هدف نهایی و اصول دستخط</h3>
|
||
<div class="subtitle">Current State Recap, Target & Coding Conventions</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>بر اساس بررسی سورس، مجوزدهی در چند نقطهی ایستا تعریف شده است و هر تغییر مستلزم انتشار مجدد تمام سرویسهاست:</p>
|
||
|
||
<table class="styled-table">
|
||
<thead><tr><th>مفهوم</th><th>محل فعلی</th><th>مشکل</th></tr></thead>
|
||
<tbody>
|
||
<tr><td><strong>Scope</strong></td><td><code>Modules/xIdentityHelper/XApiScopeHelper.cs</code> (۴ const) + <code>xIds/appsettings.json:DbSeeder.ApiScopes</code></td><td>دو منبع حقیقت؛ فقط با Seeding همگام میشوند</td></tr>
|
||
<tr><td><strong>Role</strong></td><td><code>Modules/xIdentityHelper/XUserRoles.cs</code> (۱۱ const + enum <code>XUserRole</code> با وزن ۰–۱۰) + <code>xIds/appsettings.json:XIdentity.IdentityRoles</code></td><td>وزن فقط در enum است و در DB نگهداری نمیشود</td></tr>
|
||
<tr><td><strong>Policy</strong></td><td><code>Modules/xIdentityHelper/XPolicies.cs</code> (۳۰ const) + <code>XAuthorizationHelper.GetXAuthorizationPolicies()</code> (۵۶۵ خط دستی)</td><td>لیست نقشها برای هر Policy بهصورت دستی تکرار شده</td></tr>
|
||
<tr><td><strong>Handler</strong></td><td><code>Modules/xCommons/Authorization/RequiredRolesHandler.cs</code></td><td>فقط اولین Claim <code>role</code> بررسی میشود (<code>FirstOrDefault</code>)</td></tr>
|
||
<tr><td><strong>Policy Handler</strong></td><td><code>Modules/xIdentityService/Providers/XPolicyHandler.cs</code></td><td><code>static Dictionary</code>؛ thread-safe و multi-instance نیست</td></tr>
|
||
</tbody>
|
||
</table>
|
||
|
||
<div class="highlight-box">
|
||
<strong>هدف نهایی:</strong> پس از اتمام ۱۲ گام این مستند، ادمین میتواند با یک <code>POST /authorization/policies</code> سیاست جدیدی تعریف کند که بلافاصله در xIds و تمام سرویسهای مصرفکننده (xApi، xAiApi، xAiMcpServer) با <code>[Authorize(Policy = "...")]</code> قابل استفاده باشد — بدون آنکه هیچیک از ثابتهای <code>XPolicies.*</code> موجود شکسته شوند.
|
||
</div>
|
||
|
||
<h4>اصول راهنما (دستخط پروژه — استخراجشده از xTagService و xIds)</h4>
|
||
<ul class="plain">
|
||
<li>هر ماژول <code>netstandard2.0</code>، <code>LangVersion 12.0</code>، <code>PackageId = xDashboard.<Name></code>، آیکون لینکشده از <code>Documents/Resources/Images/favicon.png</code>.</li>
|
||
<li>ساختار پوشهها: <code>Configurations/Entities</code>، <code>Constants</code>، <code>DI</code>، <code>Extensions</code>، <code>Helpers</code>، <code>Interfaces/{Entities,Dtos}</code>، <code>Models/{Entities,Dtos}</code>، <code>Providers/{Entities,Dtos,GraphQL}</code>.</li>
|
||
<li>هر Entity یک مجموعهی کامل دارد: <code>IX{E}Repository</code>، <code>X{E}EFRepository<TContext></code>، <code>X{E}MongoRepository</code>، <code>X{E}InMemoryRepository</code>، <code>IX{E}KeyGenerator</code>، <code>IX{E}RepositoryEvents</code>، <code>X{E}EntityHub</code>، <code>X{E}RepositoryProvider</code>، <code>X{E}SeederBase</code>، <code>X{E}GraphType/Query/Schema/TypeHelper</code>.</li>
|
||
<li>ثبت DI با <code>AddX{Service}<TContext>(XRepositoryType, ServiceLifetime)</code> و <code>UseX{Service}(isDevelopmentEnvironment)</code>؛ Descriptor با <code>InvokeGenericMethod</code> از Helper ساخته میشود.</li>
|
||
<li>اعتبارسنجی با <code>XException.InvalidArgs.Throw()</code> / <code>ValidationProvider.NotNull()</code>؛ خطاها در کنترلر با <code>GetExceptionActionResult(ex)</code>.</li>
|
||
<li>کنترلرهای xIds بهصورت <code>partial</code> با پسوند <code>+Feature.cs</code> و اکشنهای ادمین با <code>[RequireXPowered]</code> + <code>[Authorize(LocalApi.PolicyName)]</code> + <code>[Authorize(Policy = XPolicies.EnabledAdmin)]</code>.</li>
|
||
<li>هر بلوک منطقی با یک خط <code>//</code> خالی شروع میشود؛ متدها با XML-doc فارسی/انگلیسی و پارامترهای نامگذاریشده (<code>item: item, userInfo: userInfo</code>) صدا زده میشوند.</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۲ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۲</div>
|
||
<div class="section-title">
|
||
<h3>گام ۱ و ۲ — ایجاد پروژه و ساختار ماژول</h3>
|
||
<div class="subtitle">Step 1–2: Project Skeleton & Folder Layout</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<h4>گام ۱ — ساخت پروژهی <code>Modules/xAuthorizationService</code></h4>
|
||
<p class="no-indent">ماژول به <code>xPushService</code> (برای Hub و <code>XBaseEntityProvider</code>) و <code>xIdentityHelper</code> (برای ثابتهای <code>XUserRoles</code>/<code>XPolicies</code>/<code>XApiScopes</code> در Seeder) وابسته است. <code>xPushService</code> خود زنجیرهی <code>xIdentityService → xDataService → xModels/xCommons</code> را میآورد. بستهی <code>Microsoft.AspNetCore.Authorization</code> نیز از طریق <code>xCommons</code> (که <code>RequiredRolesRequirement</code> را دارد) در دسترس است.</p>
|
||
|
||
<div class="code-box"><span class="file">Modules/xAuthorizationService/xAuthorizationService.csproj</span><pre><Project Sdk="Microsoft.NET.Sdk">
|
||
|
||
<!-- Runtime Definition -->
|
||
<PropertyGroup>
|
||
<Version>1.0.0</Version>
|
||
<LangVersion>12.0</LangVersion>
|
||
<Authors>Hadi Khazaee Asl</Authors>
|
||
<Company>SaherElm IT Center</Company>
|
||
<PackageId>xDashboard.xAuthorizationService</PackageId>
|
||
<TargetFramework>netstandard2.0</TargetFramework>
|
||
|
||
<Description>
|
||
it is a Part of xDashboard on SaherElm IT Center which provides Dynamic
|
||
Scope / Role / Policy Management Futures ...
|
||
</Description>
|
||
|
||
<!-- Icon Definition -->
|
||
<PackageIcon>icon.png</PackageIcon>
|
||
</PropertyGroup>
|
||
|
||
<!-- Icon Handling -->
|
||
<ItemGroup>
|
||
<None Include="../../Documents/Resources/Images/favicon.png" Link="icon.png" Pack="true"
|
||
PackagePath="\icon.png" />
|
||
</ItemGroup>
|
||
|
||
<!-- Local Dependencies -->
|
||
<ItemGroup>
|
||
<ProjectReference Include="../xPushService/xPushService.csproj" />
|
||
<ProjectReference Include="../xIdentityHelper/xIdentityHelper.csproj" />
|
||
</ItemGroup>
|
||
|
||
<!-- For XML Documentation Support -->
|
||
<PropertyGroup>
|
||
<NoWarn>$(NoWarn);1591</NoWarn>
|
||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||
</PropertyGroup>
|
||
|
||
</Project></pre></div>
|
||
|
||
<div class="code-box"><span class="file">PowerShell — افزودن به Solution و ارجاع از xIds</span><pre>cd Modules
|
||
dotnet new classlib -n xAuthorizationService -f netstandard2.0
|
||
# سپس محتوای csproj بالا را جایگزین کنید
|
||
cd ..
|
||
dotnet sln add Modules/xAuthorizationService/xAuthorizationService.csproj
|
||
dotnet add xIds/xIds.csproj reference Modules/xAuthorizationService/xAuthorizationService.csproj</pre></div>
|
||
|
||
<h4>گام ۲ — ساختار پوشهها (دقیقاً مانند xTagService)</h4>
|
||
<div class="code-box"><span class="file">Modules/xAuthorizationService/ — Tree</span><pre>Configurations/Entities/
|
||
XScopeDefinitionEntityConfiguration.cs
|
||
XRoleDefinitionEntityConfiguration.cs
|
||
XPolicyDefinitionEntityConfiguration.cs
|
||
Constants/
|
||
XAuthorizationServiceConstants.cs
|
||
XPolicyKind.cs
|
||
DI/
|
||
XDIHelperExtension.cs
|
||
Extensions/
|
||
XModelExtensions.cs (Entity <-> Dto)
|
||
XPolicyDefinitionExtensions.cs (ToAuthorizationPolicy)
|
||
Helpers/
|
||
XAuthorizationServiceHelper.cs (Repository Descriptors)
|
||
Interfaces/
|
||
Entities/ IXScopeDefinition*.cs, IXRoleDefinition*.cs, IXPolicyDefinition*.cs
|
||
IXAuthorizationProvider.cs
|
||
IXScopeSyncService.cs
|
||
IXRoleSyncService.cs
|
||
IXAuthorizationCache.cs
|
||
IXRoleHierarchyResolver.cs
|
||
Models/
|
||
Entities/ XScopeDefinition.cs, XRoleDefinition.cs, XPolicyDefinition.cs
|
||
Dtos/ XScopeDefinitionDto.cs, XRoleDefinitionDto.cs, XPolicyDefinitionDto.cs,
|
||
XPolicyEvaluationResultDto.cs, XEffectiveAuthorizationDto.cs
|
||
Providers/
|
||
Entities/ X{E}EFRepository.cs, X{E}MongoRepository.cs, X{E}InMemoryRepository.cs,
|
||
X{E}KeyGenerator.cs, X{E}RepositoryEvents.cs, X{E}EntityHub.cs,
|
||
X{E}RepositoryProvider.cs, X{E}SeederBase.cs
|
||
GraphQL/ X{E}GraphType.cs, X{E}GraphQuery.cs, X{E}GraphSchema.cs, X{E}GraphQLTypeHelper.cs
|
||
XAuthorizationEntityRegisterar.cs
|
||
XAuthorizationProvider.cs (partial: +Scope, +Role, +Policy, +Evaluate)
|
||
XAuthorizationCache.cs
|
||
XRoleHierarchyResolver.cs
|
||
XDynamicPolicyProvider.cs
|
||
XAuthorizationSeeder.cs</pre></div>
|
||
|
||
<div class="info-box">
|
||
<strong>نکته:</strong> در این مستند، <code>{E}</code> بهترتیب جایگزین <code>ScopeDefinition</code>، <code>RoleDefinition</code> و <code>PolicyDefinition</code> میشود. برای جلوگیری از تکرار، فایلهای زیرساختی (Repository / Hub / KeyGenerator / Events / GraphQL) فقط برای <code>XPolicyDefinition</code> بهصورت کامل نشان داده شدهاند؛ دو موجودیت دیگر عیناً همان الگو با جایگزینی نام هستند.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۳ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۳</div>
|
||
<div class="section-title">
|
||
<h3>گام ۳ — ثابتها، موجودیتها و Dtoها</h3>
|
||
<div class="subtitle">Step 3: Constants, Entities & Dtos</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p class="no-indent">کلید همهی موجودیتها <code>string</code> است (<code>XBaseStringIDEntity</code>) و با <code>XStringKeyGenerator</code> تولید میشود؛ <code>Name</code> شناسهی منطقی و یکتاست تا با <code>[Authorize(Policy = name)]</code> و <code>RoleManager.FindByNameAsync(name)</code> همخوان باشد.</p>
|
||
|
||
<div class="code-box"><span class="file">Constants/XAuthorizationServiceConstants.cs</span><pre>namespace xAuthorizationService.Constants
|
||
{
|
||
public struct XAuthorizationServiceConstants
|
||
{
|
||
//
|
||
// Service Extensions Log Tag ...
|
||
public const string XAuthorizationServiceDILogTag = "XAuthorizationService";
|
||
|
||
//
|
||
// Table Mapping Identifiers ...
|
||
public const string XScopeDefinitionTable = "ScopeDefinitions";
|
||
public const string XRoleDefinitionTable = "RoleDefinitions";
|
||
public const string XPolicyDefinitionTable = "PolicyDefinitions";
|
||
|
||
//
|
||
// GraphQL Collection Mappings ...
|
||
public const string XScopeDefinitionSingleName = "scopeDefinition";
|
||
public const string XScopeDefinitionCollectionName = "scopeDefinitions";
|
||
public const string XRoleDefinitionSingleName = "roleDefinition";
|
||
public const string XRoleDefinitionCollectionName = "roleDefinitions";
|
||
public const string XPolicyDefinitionSingleName = "policyDefinition";
|
||
public const string XPolicyDefinitionCollectionName = "policyDefinitions";
|
||
|
||
//
|
||
// Hubs ...
|
||
public const string XScopeDefinitionEntityHub = "scopeDefinitionEntity";
|
||
public const string XRoleDefinitionEntityHub = "roleDefinitionEntity";
|
||
public const string XPolicyDefinitionEntityHub = "policyDefinitionEntity";
|
||
|
||
//
|
||
// Custome Constants ...
|
||
public const string AuthorizationChangedEvent = "authorization.changed";
|
||
public const string PolicyCacheKeyPrefix = "xauth:policy:";
|
||
public const string RolesCacheKey = "xauth:roles";
|
||
public const string ScopesCacheKey = "xauth:scopes";
|
||
public const int DefaultCacheTtlMinutes = 5;
|
||
|
||
//
|
||
// EF Repositories Helper Extensions ...
|
||
public const string GetXScopeDefinitionEFRepositoryDescriptor = "GetXScopeDefinitionEFRepositoryDescriptor";
|
||
public const string GetXRoleDefinitionEFRepositoryDescriptor = "GetXRoleDefinitionEFRepositoryDescriptor";
|
||
public const string GetXPolicyDefinitionEFRepositoryDescriptor = "GetXPolicyDefinitionEFRepositoryDescriptor";
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Constants/XPolicyKind.cs</span><pre>using xExceptions.Attributes;
|
||
|
||
namespace xAuthorizationService.Constants
|
||
{
|
||
public enum XPolicyKind
|
||
{
|
||
[StringValue("roleBased")]
|
||
RoleBased = 0,
|
||
|
||
[StringValue("scopeBased")]
|
||
ScopeBased = 1,
|
||
|
||
[StringValue("claimBased")]
|
||
ClaimBased = 2,
|
||
|
||
[StringValue("composite")]
|
||
Composite = 3
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Models/Entities/XScopeDefinition.cs</span><pre>using xModels.Base;
|
||
using System.ComponentModel.DataAnnotations;
|
||
|
||
namespace xAuthorizationService.Models.Entities
|
||
{
|
||
/// <summary>
|
||
/// a Scope Definition Model (mirror of IdentityServer ApiScope) ...
|
||
/// </summary>
|
||
public class XScopeDefinition : XBaseStringIDEntity
|
||
{
|
||
/// <summary>
|
||
/// Unique Scope Name, e.g. XAPI.read ...
|
||
/// </summary>
|
||
[Required]
|
||
[StringLength(200)]
|
||
public string Name { get; set; }
|
||
|
||
[StringLength(255)]
|
||
public string DisplayName { get; set; }
|
||
|
||
[StringLength(1000)]
|
||
public string Description { get; set; }
|
||
|
||
/// <summary>
|
||
/// Comma Separated List of User Claims ...
|
||
/// </summary>
|
||
public string UserClaims { get; set; }
|
||
|
||
/// <summary>
|
||
/// Optional ApiResource Name on IdentityServer ...
|
||
/// </summary>
|
||
[StringLength(200)]
|
||
public string ApiResourceName { get; set; }
|
||
|
||
public bool IsEnabled { get; set; } = true;
|
||
|
||
/// <summary>
|
||
/// Seeded from Constants, cannot be removed ...
|
||
/// </summary>
|
||
public bool IsSystem { get; set; }
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">Models/Entities/XRoleDefinition.cs</span><pre>using xModels.Base;
|
||
using System.ComponentModel.DataAnnotations;
|
||
|
||
namespace xAuthorizationService.Models.Entities
|
||
{
|
||
/// <summary>
|
||
/// a Role Definition Model (mirror of ASP.NET IdentityRole + Weight) ...
|
||
/// </summary>
|
||
public class XRoleDefinition : XBaseStringIDEntity
|
||
{
|
||
/// <summary>
|
||
/// Unique Normalized Role Name, e.g. chief_clerk ...
|
||
/// </summary>
|
||
[Required]
|
||
[StringLength(256)]
|
||
public string Name { get; set; }
|
||
|
||
/// <summary>
|
||
/// Persian Display Name, e.g. سر دبیر ...
|
||
/// </summary>
|
||
[StringLength(255)]
|
||
public string DisplayName { get; set; }
|
||
|
||
/// <summary>
|
||
/// Role Weight, same as XUserRole enum (user=0 ... admin=10) ...
|
||
/// </summary>
|
||
public int Weight { get; set; }
|
||
|
||
/// <summary>
|
||
/// Optional Parent Role for Inheritance ...
|
||
/// </summary>
|
||
[StringLength(256)]
|
||
public string ParentRoleName { get; set; }
|
||
|
||
public bool IsEnabled { get; set; } = true;
|
||
public bool IsSystem { get; set; }
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Models/Entities/XPolicyDefinition.cs</span><pre>using xModels.Base;
|
||
using xAuthorizationService.Constants;
|
||
using System.ComponentModel.DataAnnotations;
|
||
|
||
namespace xAuthorizationService.Models.Entities
|
||
{
|
||
/// <summary>
|
||
/// a Policy Definition Model which can be converted to AuthorizationPolicy ...
|
||
/// </summary>
|
||
public class XPolicyDefinition : XBaseStringIDEntity
|
||
{
|
||
/// <summary>
|
||
/// Unique Policy Name, e.g. enabledEditorPolicy ...
|
||
/// </summary>
|
||
[Required]
|
||
[StringLength(200)]
|
||
public string Name { get; set; }
|
||
|
||
[StringLength(255)]
|
||
public string DisplayName { get; set; }
|
||
|
||
public XPolicyKind Kind { get; set; } = XPolicyKind.RoleBased;
|
||
|
||
/// <summary>
|
||
/// Comma Separated Role Names (explicit list) ...
|
||
/// </summary>
|
||
public string RequiredRoles { get; set; }
|
||
|
||
/// <summary>
|
||
/// if provided, all Roles with Weight >= MinRoleWeight will be Injected ...
|
||
/// </summary>
|
||
public int? MinRoleWeight { get; set; }
|
||
|
||
/// <summary>
|
||
/// Comma Separated Scope Names ...
|
||
/// </summary>
|
||
public string RequiredScopes { get; set; }
|
||
|
||
/// <summary>
|
||
/// Json Array of { "Type": "...", "Values": ["..."] } ...
|
||
/// </summary>
|
||
public string RequiredClaims { get; set; }
|
||
|
||
/// <summary>
|
||
/// Requires IsBanned=false and IsEnabled=true Claims ...
|
||
/// </summary>
|
||
public bool RequireEnabledUser { get; set; }
|
||
|
||
public bool RequireAuthenticatedUser { get; set; } = true;
|
||
public bool IsEnabled { get; set; } = true;
|
||
public bool IsSystem { get; set; }
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Models/Dtos/XPolicyDefinitionDto.cs (Scope/Role Dto به همین شکل)</span><pre>using xModels.Base;
|
||
using xAuthorizationService.Constants;
|
||
using System.Collections.Generic;
|
||
|
||
namespace xAuthorizationService.Models.Dtos
|
||
{
|
||
public class XPolicyDefinitionDto : XBaseStringIDEntityDto
|
||
{
|
||
public string Name { get; set; }
|
||
public string DisplayName { get; set; }
|
||
public XPolicyKind Kind { get; set; }
|
||
public List<string> RequiredRoles { get; set; }
|
||
public int? MinRoleWeight { get; set; }
|
||
public List<string> RequiredScopes { get; set; }
|
||
public List<XRequiredClaimDto> RequiredClaims { get; set; }
|
||
public bool RequireEnabledUser { get; set; }
|
||
public bool RequireAuthenticatedUser { get; set; } = true;
|
||
public bool IsEnabled { get; set; } = true;
|
||
public bool IsSystem { get; set; }
|
||
|
||
/// <summary>
|
||
/// Read-only: Roles after Hierarchy Resolve ...
|
||
/// </summary>
|
||
public List<string> EffectiveRoles { get; set; }
|
||
}
|
||
|
||
public class XRequiredClaimDto
|
||
{
|
||
public string Type { get; set; }
|
||
public List<string> Values { get; set; }
|
||
}
|
||
|
||
public class XPolicyEvaluationResultDto
|
||
{
|
||
public string Policy { get; set; }
|
||
public bool Passed { get; set; }
|
||
public List<string> FailedRequirements { get; set; } = new List<string>();
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Configurations/Entities/XPolicyDefinitionEntityConfiguration.cs</span><pre>using xDataService.Providers;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using xAuthorizationService.Constants;
|
||
using xAuthorizationService.Models.Entities;
|
||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||
|
||
namespace xAuthorizationService.Configurations.Entities
|
||
{
|
||
public class XPolicyDefinitionEntityConfiguration : XBaseEntityTypeConfiguration<XPolicyDefinition, string>
|
||
{
|
||
public override void Configure(EntityTypeBuilder<XPolicyDefinition> builder)
|
||
{
|
||
//
|
||
builder.ToTable(XAuthorizationServiceConstants.XPolicyDefinitionTable);
|
||
|
||
//
|
||
builder.HasIndex(p => p.Name).IsUnique();
|
||
}
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="warning-box">
|
||
<strong>نکتهی سازگاری:</strong> ماژولها روی <code>EF Core 3.1.14</code> و <code>xIds</code> روی <code>5.0.2</code> است. <code>HasIndex().IsUnique()</code> و <code>ToTable()</code> در هر دو نسخه یکساناند. از <code>HasConversion</code> برای لیستها استفاده نکنید؛ طبق الگوی <code>XTag.References</code> رشتهی Comma-Separated نگه دارید و تبدیل را در <code>XModelExtensions</code> انجام دهید.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۴ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۴</div>
|
||
<div class="section-title">
|
||
<h3>گام ۴ — زیرساخت Repository / Hub / GraphQL (Blueprint)</h3>
|
||
<div class="subtitle">Step 4: Repository, Hub, KeyGenerator, Events, GraphQL per Entity</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p class="no-indent">برای هر سه موجودیت، فایلهای زیر دقیقاً با الگوی <code>xTagService</code> ساخته میشوند. نمونه برای <code>XPolicyDefinition</code>:</p>
|
||
|
||
<div class="code-box"><span class="file">Interfaces/Entities/IXPolicyDefinition*.cs (۷ اینترفیس کوچک)</span><pre>using xDataService.Interfaces;
|
||
using xPushService.Interfaces;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Providers.Entities;
|
||
|
||
namespace xAuthorizationService.Interfaces.Entities
|
||
{
|
||
public interface IXPolicyDefinitionRepository : IXBaseRepository<XPolicyDefinition, string> { }
|
||
public interface IXPolicyDefinitionKeyGenerator : IXKeyGenerator<XPolicyDefinition, string> { }
|
||
public interface IXPolicyDefinitionRepositoryEvents : IXBaseRepositoryEvents<XPolicyDefinition> { }
|
||
public interface IXPolicyDefinitionEntityHub : IXBaseEntityHub<XPolicyDefinition, string> { }
|
||
public interface IXPolicyDefinitionSeeder : IXBaseDbSeeder<XPolicyDefinition, string> { }
|
||
public interface IXPolicyDefinitionGraphQLTypeHelper : IXBaseGraphQLTypeHelper<XPolicyDefinition, string> { }
|
||
public interface IXPolicyDefinitionRepositoryProvider
|
||
: IXBaseEntityProvider<XPolicyDefinition, string, XPolicyDefinitionEntityHub> { }
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Providers/Entities/XPolicyDefinitionKeyGenerator.cs + RepositoryEvents + EntityHub</span><pre>using xDataService.Providers;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Providers.Entities
|
||
{
|
||
public class XPolicyDefinitionKeyGenerator : XStringKeyGenerator<XPolicyDefinition>, IXPolicyDefinitionKeyGenerator
|
||
{ }
|
||
|
||
public class XPolicyDefinitionRepositoryEvents : XBaseRepositoryEvents<XPolicyDefinition>, IXPolicyDefinitionRepositoryEvents
|
||
{ }
|
||
}
|
||
|
||
// ----- XPolicyDefinitionEntityHub.cs -----
|
||
using xPushService.Base;
|
||
using Microsoft.Extensions.Logging;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Providers.Entities
|
||
{
|
||
public class XPolicyDefinitionEntityHub : XBaseEntityHub<XPolicyDefinition, string>, IXPolicyDefinitionEntityHub
|
||
{
|
||
public XPolicyDefinitionEntityHub(
|
||
ILogger<XPolicyDefinitionEntityHub> logger
|
||
) : base(logger)
|
||
{ }
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Providers/Entities/XPolicyDefinitionEFRepository.cs (+ Mongo / InMemory)</span><pre>using xDataService.Db;
|
||
using xDataService.Providers;
|
||
using xDataService.Interfaces;
|
||
using xDataService.Configuration;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Providers.Entities
|
||
{
|
||
public class XPolicyDefinitionEFRepository<TContext>
|
||
: XBaseEFRepository<XPolicyDefinition, string, TContext>, IXPolicyDefinitionRepository
|
||
where TContext : XDbContext
|
||
{
|
||
public XPolicyDefinitionEFRepository(
|
||
IXUnitOfWorks<TContext> unitOfWorks,
|
||
XDataServiceConfiguration configuration,
|
||
IXPolicyDefinitionKeyGenerator keyGenerator = null,
|
||
IXPolicyDefinitionRepositoryEvents baseRepositoryEvents = null
|
||
) : base(
|
||
unitOfWorks,
|
||
configuration,
|
||
keyGenerator,
|
||
baseRepositoryEvents
|
||
)
|
||
{ }
|
||
}
|
||
|
||
public class XPolicyDefinitionMongoRepository
|
||
: XBaseMongoRepository<XPolicyDefinition, string>, IXPolicyDefinitionRepository
|
||
{
|
||
public XPolicyDefinitionMongoRepository(
|
||
XDataBaseConfiguration dbConfiguration,
|
||
XDataServiceConfiguration configuration,
|
||
string collectionName = null,
|
||
IXPolicyDefinitionKeyGenerator keyGenerator = null,
|
||
IXPolicyDefinitionRepositoryEvents baseRepositoryEvents = null
|
||
) : base(
|
||
dbConfiguration,
|
||
configuration,
|
||
collectionName,
|
||
keyGenerator,
|
||
baseRepositoryEvents
|
||
)
|
||
{ }
|
||
}
|
||
|
||
public class XPolicyDefinitionInMemoryRepository
|
||
: XBaseInMemoryRepository<XPolicyDefinition, string>, IXPolicyDefinitionRepository
|
||
{
|
||
public XPolicyDefinitionInMemoryRepository(
|
||
XDataServiceConfiguration configuration,
|
||
IXPolicyDefinitionKeyGenerator keyGenerator = null,
|
||
IXPolicyDefinitionRepositoryEvents baseRepositoryEvents = null
|
||
) : base(
|
||
configuration,
|
||
keyGenerator,
|
||
baseRepositoryEvents
|
||
)
|
||
{ }
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">Providers/Entities/XPolicyDefinitionRepositoryProvider.cs + XPolicyDefinitionSeederBase.cs</span><pre>using xPushService.Base;
|
||
using xDataService.Configuration;
|
||
using xIdentityService.Interfaces;
|
||
using Microsoft.AspNetCore.SignalR;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Providers.Entities
|
||
{
|
||
public class XPolicyDefinitionRepositoryProvider
|
||
: XBaseEntityProvider<XPolicyDefinition, string, XPolicyDefinitionEntityHub>, IXPolicyDefinitionRepositoryProvider
|
||
{
|
||
public XPolicyDefinitionRepositoryProvider(
|
||
IHubContext<XPolicyDefinitionEntityHub> hub,
|
||
IXPolicyDefinitionRepository repository,
|
||
XDataServiceConfiguration dataConfiguration,
|
||
IXIdentityProvider identityProvider = null
|
||
) : base(
|
||
hub,
|
||
repository,
|
||
dataConfiguration,
|
||
identityProvider
|
||
)
|
||
{ }
|
||
}
|
||
}
|
||
|
||
// ----- XPolicyDefinitionSeederBase.cs -----
|
||
using xDataService.Providers;
|
||
using xDataService.Configuration;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Providers.Entities
|
||
{
|
||
public abstract class XPolicyDefinitionSeederBase : XBaseDbSeeder<XPolicyDefinition, string>, IXPolicyDefinitionSeeder
|
||
{
|
||
protected XPolicyDefinitionSeederBase(
|
||
string entity,
|
||
string database,
|
||
IXPolicyDefinitionRepository repository,
|
||
XDataServiceConfiguration dataServiceConfiguration
|
||
) : base(
|
||
entity,
|
||
database,
|
||
repository,
|
||
dataServiceConfiguration
|
||
)
|
||
{ }
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Providers/GraphQL/XPolicyDefinition{GraphType,GraphQuery,GraphSchema,GraphQLTypeHelper}.cs</span><pre>using System;
|
||
using GraphQL.Types;
|
||
using xDataService.GraphQL;
|
||
using xDataService.Configuration;
|
||
using xAuthorizationService.Constants;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Providers.GraphQL
|
||
{
|
||
public class XPolicyDefinitionGraphType : XBaseGraphObjectType<XPolicyDefinition, string>
|
||
{
|
||
public XPolicyDefinitionGraphType() : base()
|
||
{
|
||
Field(x => x.Name);
|
||
Field(x => x.DisplayName, nullable: true);
|
||
Field(x => x.Kind);
|
||
Field(x => x.RequiredRoles, nullable: true);
|
||
Field(x => x.MinRoleWeight, nullable: true);
|
||
Field(x => x.RequiredScopes, nullable: true);
|
||
Field(x => x.RequiredClaims, nullable: true);
|
||
Field(x => x.RequireEnabledUser);
|
||
Field(x => x.RequireAuthenticatedUser);
|
||
Field(x => x.IsEnabled);
|
||
Field(x => x.IsSystem);
|
||
}
|
||
}
|
||
|
||
public class XPolicyDefinitionGraphQuery
|
||
: XBaseGraphQLQuery<XPolicyDefinition, string, XPolicyDefinitionGraphType, StringGraphType>
|
||
{
|
||
public XPolicyDefinitionGraphQuery(
|
||
XDataServiceConfiguration configuration,
|
||
IXPolicyDefinitionRepository repository,
|
||
IXPolicyDefinitionGraphQLTypeHelper helper
|
||
) : base(
|
||
configuration,
|
||
repository,
|
||
helper
|
||
)
|
||
{ }
|
||
}
|
||
|
||
public class XPolicyDefinitionGraphSchema : Schema
|
||
{
|
||
public XPolicyDefinitionGraphSchema(IServiceProvider services) : base(services)
|
||
{
|
||
Query = (XPolicyDefinitionGraphQuery)services.GetService(typeof(XPolicyDefinitionGraphQuery));
|
||
}
|
||
}
|
||
|
||
public class XPolicyDefinitionGraphQLTypeHelper
|
||
: XBaseGraphQLTypeHelper<XPolicyDefinition, string>, IXPolicyDefinitionGraphQLTypeHelper
|
||
{
|
||
public XPolicyDefinitionGraphQLTypeHelper(
|
||
XDataServiceConfiguration configuration
|
||
) : base(configuration)
|
||
{ }
|
||
|
||
public override string GetInQueryCollectionName()
|
||
{
|
||
return XAuthorizationServiceConstants.XPolicyDefinitionCollectionName;
|
||
}
|
||
|
||
public override string GetInQuerySingleName()
|
||
{
|
||
return XAuthorizationServiceConstants.XPolicyDefinitionSingleName;
|
||
}
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">Providers/XAuthorizationEntityRegisterar.cs</span><pre>using xDataService.Providers;
|
||
using xDataService.Interfaces;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Configurations.Entities;
|
||
|
||
namespace xAuthorizationService.Providers
|
||
{
|
||
public class XAuthorizationEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar
|
||
{
|
||
public XAuthorizationEntityRegisterar()
|
||
: base(nameof(XAuthorizationEntityRegisterar))
|
||
{
|
||
//
|
||
// Add Authorization Entities ...
|
||
AddEntity<XScopeDefinition, string>();
|
||
AddEntity<XRoleDefinition, string>();
|
||
AddEntity<XPolicyDefinition, string>();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Configure Entities ...
|
||
/// </summary>
|
||
/// <param name="modelBuilder"></param>
|
||
public override void ConfigureEntities(ModelBuilder modelBuilder)
|
||
{
|
||
//
|
||
// Configure Entity Using Provided ...
|
||
modelBuilder
|
||
.ApplyConfigurationsFromAssembly(typeof(XPolicyDefinitionEntityConfiguration).Assembly);
|
||
|
||
//
|
||
base.ConfigureEntities(modelBuilder);
|
||
}
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="success-box">
|
||
<strong>چکلیست گام ۴:</strong> برای هر یک از ۳ موجودیت: ۷ اینترفیس + ۳ Repository + KeyGenerator + Events + Hub + RepositoryProvider + SeederBase + ۴ کلاس GraphQL ≈ <strong>۱۸ فایل × ۳ = ۵۴ فایل</strong>. همگی بدون منطق تجاری و فقط Wiring هستند؛ با Find/Replace روی نمونهی <code>PolicyDefinition</code> تولید کنید. پس از این گام <code>dotnet build Modules/xAuthorizationService</code> باید بدون خطا باشد.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۵ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۵</div>
|
||
<div class="section-title">
|
||
<h3>گام ۵ — Helper Descriptorها و ثبت DI</h3>
|
||
<div class="subtitle">Step 5: Repository Descriptors & XDIHelperExtension</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p class="no-indent"><code>XAuthorizationServiceHelper</code> برای هر موجودیت سه متد Descriptor (EF/Mongo/InMemory) دارد؛ نمونهی EF برای <code>XPolicyDefinition</code>:</p>
|
||
|
||
<div class="code-box"><span class="file">Helpers/XAuthorizationServiceHelper.cs (بخش PolicyDefinition — EF)</span><pre>using GraphQL.Types;
|
||
using xDataService.Db;
|
||
using xDataService.Models;
|
||
using xDataService.Providers;
|
||
using xAuthorizationService.Models.Entities;
|
||
using xAuthorizationService.Providers.GraphQL;
|
||
using xAuthorizationService.Providers.Entities;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Helpers
|
||
{
|
||
public static partial class XAuthorizationServiceHelper
|
||
{
|
||
//
|
||
#region PolicyDefinition EF Repository Descriptor Provider(s) ...
|
||
public static XEFRepositoryDescriptor<
|
||
XPolicyDefinition,
|
||
string,
|
||
IXPolicyDefinitionKeyGenerator,
|
||
XPolicyDefinitionKeyGenerator,
|
||
IXPolicyDefinitionRepositoryEvents,
|
||
XPolicyDefinitionRepositoryEvents,
|
||
XPolicyDefinitionGraphType,
|
||
StringGraphType,
|
||
XPolicyDefinitionGraphQuery,
|
||
IXPolicyDefinitionGraphQLTypeHelper,
|
||
XPolicyDefinitionGraphQLTypeHelper,
|
||
XPolicyDefinitionGraphSchema,
|
||
IXPolicyDefinitionRepository,
|
||
XPolicyDefinitionEFRepository<TContext>,
|
||
TContext
|
||
> GetXPolicyDefinitionEFRepositoryDescriptor<TContext>()
|
||
where TContext : XDbContext
|
||
{
|
||
//
|
||
var result = new XEFRepositoryDescriptor<
|
||
XPolicyDefinition,
|
||
string,
|
||
IXPolicyDefinitionKeyGenerator,
|
||
XPolicyDefinitionKeyGenerator,
|
||
IXPolicyDefinitionRepositoryEvents,
|
||
XPolicyDefinitionRepositoryEvents,
|
||
XPolicyDefinitionGraphType,
|
||
StringGraphType,
|
||
XPolicyDefinitionGraphQuery,
|
||
IXPolicyDefinitionGraphQLTypeHelper,
|
||
XPolicyDefinitionGraphQLTypeHelper,
|
||
XPolicyDefinitionGraphSchema,
|
||
IXPolicyDefinitionRepository,
|
||
XPolicyDefinitionEFRepository<TContext>,
|
||
TContext
|
||
>();
|
||
|
||
//
|
||
return result;
|
||
}
|
||
#endregion
|
||
|
||
//
|
||
// GetXPolicyDefinitionMongoRepositoryDescriptor()
|
||
// GetXPolicyDefinitionInMemoryRepositoryDescriptor()
|
||
// ... exactly as XTagServiceHelper ...
|
||
}
|
||
}</pre></div>
|
||
|
||
<p class="no-indent">در <code>XDIHelperExtension</code> سه Descriptor ساخته و با <code>AddXRepository</code> ثبت میشوند، سپس سرویسهای منطقی اضافه میگردند:</p>
|
||
|
||
<div class="code-box"><span class="file">DI/XDIHelperExtension.cs</span><pre>using System;
|
||
using xDataService.Db;
|
||
using xDataService.DI;
|
||
using xPushService.DI;
|
||
using xCommons.Helpers;
|
||
using xCommons.Extensions;
|
||
using xDataService.Models;
|
||
using xPushService.Helpers;
|
||
using xExceptions.Constants;
|
||
using xDataService.Constants;
|
||
using Microsoft.AspNetCore.Builder;
|
||
using xAuthorizationService.Helpers;
|
||
using xAuthorizationService.Constants;
|
||
using xAuthorizationService.Providers;
|
||
using xAuthorizationService.Interfaces;
|
||
using Microsoft.AspNetCore.Authorization;
|
||
using xAuthorizationService.Providers.Entities;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
using Microsoft.Extensions.DependencyInjection;
|
||
|
||
namespace xAuthorizationService.DI
|
||
{
|
||
public static class XDIHelperExtension
|
||
{
|
||
/// <summary>
|
||
/// Register Service ...
|
||
/// </summary>
|
||
public static void AddXAuthorizationService<TContext>(
|
||
this IServiceCollection services,
|
||
XRepositoryType repositoryType,
|
||
ServiceLifetime lifeTime = ServiceLifetime.Scoped
|
||
)
|
||
where TContext : XDbContext
|
||
{
|
||
AddAuthorizationService(
|
||
services: services,
|
||
lifeTime: lifeTime,
|
||
contextType: typeof(TContext),
|
||
repositoryType: repositoryType
|
||
);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Register Service (Mongo / InMemory) ...
|
||
/// </summary>
|
||
public static void AddXAuthorizationService(
|
||
this IServiceCollection services,
|
||
XRepositoryType repositoryType,
|
||
ServiceLifetime lifeTime = ServiceLifetime.Scoped
|
||
)
|
||
{
|
||
AddAuthorizationService(
|
||
contextType: null,
|
||
services: services,
|
||
lifeTime: lifeTime,
|
||
repositoryType: repositoryType
|
||
);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Replace Default Policy Provider with Dynamic One ...
|
||
/// Call it on Consumers too (xApi, xAiApi, ...) ...
|
||
/// </summary>
|
||
public static void AddXDynamicPolicyProvider(this IServiceCollection services)
|
||
{
|
||
//
|
||
services.AddMemoryCache();
|
||
services.AddSingleton<IXAuthorizationCache, XAuthorizationCache>();
|
||
services.AddSingleton<IAuthorizationPolicyProvider, XDynamicPolicyProvider>();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Use XAuthorizationService Middleware ...
|
||
/// </summary>
|
||
public static void UseXAuthorizationService(
|
||
this IApplicationBuilder app,
|
||
bool isDevelopmentEnvironment = false
|
||
)
|
||
{
|
||
//
|
||
#region Using XAuthorization Hubs ...
|
||
//
|
||
var pushHelper = new XPushServiceHelper();
|
||
|
||
//
|
||
pushHelper.AddHub<XScopeDefinitionEntityHub>(XAuthorizationServiceConstants.XScopeDefinitionEntityHub);
|
||
pushHelper.AddHub<XRoleDefinitionEntityHub>(XAuthorizationServiceConstants.XRoleDefinitionEntityHub);
|
||
pushHelper.AddHub<XPolicyDefinitionEntityHub>(XAuthorizationServiceConstants.XPolicyDefinitionEntityHub);
|
||
|
||
//
|
||
app.UseXPushService(pushHelper);
|
||
#endregion
|
||
|
||
//
|
||
// Using Repository Descriptors ...
|
||
foreach (var descriptor in descriptors)
|
||
{
|
||
//
|
||
if (!descriptor.IsNull())
|
||
{
|
||
app.UseXRepository(
|
||
descriptor: descriptor,
|
||
isDevelopmentEnvironment: isDevelopmentEnvironment
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
//
|
||
#region Private ...
|
||
private static readonly XRepositoryDescriptor[] descriptors = new XRepositoryDescriptor[3];
|
||
|
||
/// <summary>
|
||
/// a LogTag for Service ...
|
||
/// </summary>
|
||
private static string XLogTag = XAuthorizationServiceConstants.XAuthorizationServiceDILogTag;
|
||
|
||
/// <summary>
|
||
/// print a log in Console ...
|
||
/// </summary>
|
||
private static void Log(string message)
|
||
{
|
||
Console.WriteLine($"{XLogTag} => {message}");
|
||
}
|
||
|
||
private static void AddAuthorizationService(
|
||
IServiceCollection services,
|
||
XRepositoryType repositoryType,
|
||
Type contextType = null,
|
||
ServiceLifetime lifeTime = ServiceLifetime.Scoped
|
||
)
|
||
{
|
||
//
|
||
var exception = XException.InvalidArgs.ToException();
|
||
|
||
//
|
||
// Validate Repository Type ... (same as XTagService)
|
||
var isRepositoryTypeValid =
|
||
(repositoryType == XRepositoryType.EF && !contextType.IsNull()) ||
|
||
((repositoryType == XRepositoryType.Mongo ||
|
||
repositoryType == XRepositoryType.InMemory) && contextType.IsNull());
|
||
if (services.IsNull() || !isRepositoryTypeValid)
|
||
{
|
||
//
|
||
Log("Service Registration failed, Invalid Repository Type and Context Type ...");
|
||
throw exception;
|
||
}
|
||
|
||
//
|
||
// Make Instance of Repository Descriptors Based on Provided Type ...
|
||
switch (repositoryType)
|
||
{
|
||
//
|
||
case XRepositoryType.EF:
|
||
descriptors[0] = typeof(XAuthorizationServiceHelper)
|
||
.InvokeGenericMethod<XRepositoryDescriptor>(
|
||
args: null,
|
||
runtimeType: contextType,
|
||
methodName: XAuthorizationServiceConstants.GetXScopeDefinitionEFRepositoryDescriptor
|
||
);
|
||
descriptors[1] = typeof(XAuthorizationServiceHelper)
|
||
.InvokeGenericMethod<XRepositoryDescriptor>(
|
||
args: null,
|
||
runtimeType: contextType,
|
||
methodName: XAuthorizationServiceConstants.GetXRoleDefinitionEFRepositoryDescriptor
|
||
);
|
||
descriptors[2] = typeof(XAuthorizationServiceHelper)
|
||
.InvokeGenericMethod<XRepositoryDescriptor>(
|
||
args: null,
|
||
runtimeType: contextType,
|
||
methodName: XAuthorizationServiceConstants.GetXPolicyDefinitionEFRepositoryDescriptor
|
||
);
|
||
break;
|
||
|
||
//
|
||
case XRepositoryType.Mongo:
|
||
descriptors[0] = XAuthorizationServiceHelper.GetXScopeDefinitionMongoRepositoryDescriptor();
|
||
descriptors[1] = XAuthorizationServiceHelper.GetXRoleDefinitionMongoRepositoryDescriptor();
|
||
descriptors[2] = XAuthorizationServiceHelper.GetXPolicyDefinitionMongoRepositoryDescriptor();
|
||
break;
|
||
|
||
//
|
||
case XRepositoryType.InMemory:
|
||
descriptors[0] = XAuthorizationServiceHelper.GetXScopeDefinitionInMemoryRepositoryDescriptor();
|
||
descriptors[1] = XAuthorizationServiceHelper.GetXRoleDefinitionInMemoryRepositoryDescriptor();
|
||
descriptors[2] = XAuthorizationServiceHelper.GetXPolicyDefinitionInMemoryRepositoryDescriptor();
|
||
break;
|
||
}
|
||
|
||
//
|
||
// Register Repository Descriptors ...
|
||
foreach (var descriptor in descriptors)
|
||
{
|
||
services.AddXRepository(
|
||
lifeTime: lifeTime,
|
||
descriptor: descriptor
|
||
);
|
||
}
|
||
|
||
//
|
||
// Register Entity Providers ...
|
||
services.Add(new ServiceDescriptor(typeof(IXScopeDefinitionRepositoryProvider), typeof(XScopeDefinitionRepositoryProvider), lifeTime));
|
||
services.Add(new ServiceDescriptor(typeof(IXRoleDefinitionRepositoryProvider), typeof(XRoleDefinitionRepositoryProvider), lifeTime));
|
||
services.Add(new ServiceDescriptor(typeof(IXPolicyDefinitionRepositoryProvider), typeof(XPolicyDefinitionRepositoryProvider), lifeTime));
|
||
|
||
//
|
||
// Register Domain Services ...
|
||
services.Add(new ServiceDescriptor(typeof(IXRoleHierarchyResolver), typeof(XRoleHierarchyResolver), lifeTime));
|
||
services.Add(new ServiceDescriptor(typeof(IXAuthorizationProvider), typeof(XAuthorizationProvider), lifeTime));
|
||
|
||
//
|
||
Log("Service Regitration Succeed ...");
|
||
}
|
||
#endregion
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="info-box">
|
||
<strong>چرا <code>IXAuthorizationCache</code> و <code>IAuthorizationPolicyProvider</code> Singleton هستند؟</strong> ASP.NET Core <code>IAuthorizationPolicyProvider</code> را یکبار resolve میکند و در <code>AuthorizationMiddleware</code> نگه میدارد؛ بنابراین نمیتواند مستقیم به Repository (Scoped) وابسته باشد. <code>XDynamicPolicyProvider</code> از <code>IServiceScopeFactory</code> برای ایجاد Scope موقت هنگام cache-miss استفاده میکند (گام ۷).
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۶ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۶</div>
|
||
<div class="section-title">
|
||
<h3>گام ۶ — Role Hierarchy Resolver و Policy Builder</h3>
|
||
<div class="subtitle">Step 6: XRoleHierarchyResolver & ToAuthorizationPolicy()</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p class="no-indent">این دو جزء قلب ماژول هستند: اولی لیست دستی و تکراری نقشها در <code>XAuthorizationHelper</code> را با یک محاسبهی مبتنی بر <code>Weight</code> جایگزین میکند و دومی <code>XPolicyDefinition</code> را دقیقاً به همان <code>AuthorizationPolicy</code> تبدیل میکند که امروز بهصورت دستی ساخته میشود.</p>
|
||
|
||
<div class="code-box"><span class="file">Interfaces/IXRoleHierarchyResolver.cs + Providers/XRoleHierarchyResolver.cs</span><pre>using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using System.Collections.Generic;
|
||
|
||
namespace xAuthorizationService.Interfaces
|
||
{
|
||
public interface IXRoleHierarchyResolver
|
||
{
|
||
/// <summary>
|
||
/// Retrieve All Enabled Role Names which Weight >= minWeight ...
|
||
/// </summary>
|
||
Task<IEnumerable<string>> GetRolesByMinWeightAsync(
|
||
int minWeight,
|
||
CancellationToken cancellationToken = default
|
||
);
|
||
|
||
/// <summary>
|
||
/// Retrieve Effective Roles for a Policy
|
||
/// (explicit RequiredRoles ∪ roles by MinRoleWeight ∪ parents chain) ...
|
||
/// </summary>
|
||
Task<IEnumerable<string>> ResolveEffectiveRolesAsync(
|
||
IEnumerable<string> explicitRoles,
|
||
int? minRoleWeight,
|
||
CancellationToken cancellationToken = default
|
||
);
|
||
}
|
||
}
|
||
|
||
// ----- Providers/XRoleHierarchyResolver.cs -----
|
||
using System;
|
||
using System.Linq;
|
||
using System.Threading;
|
||
using xCommons.Extensions;
|
||
using System.Threading.Tasks;
|
||
using System.Collections.Generic;
|
||
using xAuthorizationService.Interfaces;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Providers
|
||
{
|
||
public class XRoleHierarchyResolver : IXRoleHierarchyResolver
|
||
{
|
||
private readonly IXRoleDefinitionRepository repository;
|
||
|
||
public XRoleHierarchyResolver(
|
||
IXRoleDefinitionRepository repository
|
||
)
|
||
{
|
||
this.repository = repository;
|
||
}
|
||
|
||
public async Task<IEnumerable<string>> GetRolesByMinWeightAsync(
|
||
int minWeight,
|
||
CancellationToken cancellationToken = default
|
||
)
|
||
{
|
||
//
|
||
var roles = await repository.FindManyAsync(
|
||
predicate: r => r.IsEnabled && r.Weight >= minWeight,
|
||
orderBuilder: q => q.OrderBy(r => r.Weight),
|
||
cancellationToken: cancellationToken
|
||
);
|
||
|
||
//
|
||
return roles
|
||
.Select(r => r.Name.ToNormalString())
|
||
.Distinct()
|
||
.ToList();
|
||
}
|
||
|
||
public async Task<IEnumerable<string>> ResolveEffectiveRolesAsync(
|
||
IEnumerable<string> explicitRoles,
|
||
int? minRoleWeight,
|
||
CancellationToken cancellationToken = default
|
||
)
|
||
{
|
||
//
|
||
var result = new HashSet<string>(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 repository.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.ToList();
|
||
}
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">Extensions/XPolicyDefinitionExtensions.cs</span><pre>using System;
|
||
using System.Linq;
|
||
using IdentityModel;
|
||
using Newtonsoft.Json;
|
||
using xCommons.Constants;
|
||
using xCommons.Extensions;
|
||
using xCommons.Authorization;
|
||
using System.Collections.Generic;
|
||
using xAuthorizationService.Models.Dtos;
|
||
using Microsoft.AspNetCore.Authorization;
|
||
using xAuthorizationService.Models.Entities;
|
||
|
||
namespace xAuthorizationService.Extensions
|
||
{
|
||
public static class XPolicyDefinitionExtensions
|
||
{
|
||
/// <summary>
|
||
/// Split Comma Separated Values (same style as XTag.References) ...
|
||
/// </summary>
|
||
public static List<string> ToCsvList(this string source)
|
||
{
|
||
//
|
||
if (source.IsNullOrEmpty())
|
||
{
|
||
return new List<string>();
|
||
}
|
||
|
||
//
|
||
return source
|
||
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
|
||
.Select(s => s.Trim())
|
||
.Where(s => !s.IsNullOrEmpty())
|
||
.Distinct()
|
||
.ToList();
|
||
}
|
||
|
||
public static string ToCsv(this IEnumerable<string> source)
|
||
{
|
||
return source.HasChild() ? string.Join(",", source.Distinct()) : null;
|
||
}
|
||
|
||
public static List<XRequiredClaimDto> ToRequiredClaims(this string json)
|
||
{
|
||
//
|
||
if (json.IsNullOrEmpty())
|
||
{
|
||
return new List<XRequiredClaimDto>();
|
||
}
|
||
|
||
//
|
||
try
|
||
{
|
||
return JsonConvert.DeserializeObject<List<XRequiredClaimDto>>(json)
|
||
?? new List<XRequiredClaimDto>();
|
||
}
|
||
catch
|
||
{
|
||
return new List<XRequiredClaimDto>();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Build AuthorizationPolicy exactly like XAuthorizationHelper does ...
|
||
/// </summary>
|
||
/// <param name="source"></param>
|
||
/// <param name="effectiveRoles">already resolved by IXRoleHierarchyResolver</param>
|
||
public static AuthorizationPolicy ToAuthorizationPolicy(
|
||
this XPolicyDefinition source,
|
||
IEnumerable<string> 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.ToCsvList();
|
||
if (scopes.HasChild())
|
||
{
|
||
builder.RequireClaim(JwtClaimTypes.Scope, scopes.ToArray());
|
||
}
|
||
|
||
//
|
||
// 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()
|
||
);
|
||
}
|
||
|
||
//
|
||
return builder.Build();
|
||
}
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="success-box">
|
||
<strong>معادلسازی با کد فعلی:</strong> Policy <code>enabledChiefClerkPolicy</code> امروز = <code>RequireAuthenticatedUser + RequiredRolesRequirement[chief_clerk, journalist, responsible_manager, admin] + IsBanned=false + IsEnabled=true</code>. با این ماژول همان Policy = رکورد <code>{ Name: "enabledChiefClerkPolicy", Kind: RoleBased, MinRoleWeight: 7, RequireEnabledUser: true }</code>. تست واحد گام ۱۲ دقیقاً این تساوی را بررسی میکند.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۷ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۷</div>
|
||
<div class="section-title">
|
||
<h3>گام ۷ — Cache و XDynamicPolicyProvider</h3>
|
||
<div class="subtitle">Step 7: IXAuthorizationCache & IAuthorizationPolicyProvider</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<div class="code-box"><span class="file">Interfaces/IXAuthorizationCache.cs + Providers/XAuthorizationCache.cs</span><pre>using Microsoft.AspNetCore.Authorization;
|
||
|
||
namespace xAuthorizationService.Interfaces
|
||
{
|
||
public interface IXAuthorizationCache
|
||
{
|
||
bool TryGetPolicy(string name, out AuthorizationPolicy policy);
|
||
void SetPolicy(string name, AuthorizationPolicy policy);
|
||
void RemovePolicy(string name);
|
||
void Clear();
|
||
}
|
||
}
|
||
|
||
// ----- Providers/XAuthorizationCache.cs -----
|
||
using System;
|
||
using xCommons.Extensions;
|
||
using System.Collections.Concurrent;
|
||
using xAuthorizationService.Constants;
|
||
using xAuthorizationService.Interfaces;
|
||
using Microsoft.AspNetCore.Authorization;
|
||
using Microsoft.Extensions.Caching.Memory;
|
||
|
||
namespace xAuthorizationService.Providers
|
||
{
|
||
/// <summary>
|
||
/// Thread-safe local cache; IMemoryCache gives TTL,
|
||
/// ConcurrentDictionary gives key tracking for Clear() ...
|
||
/// </summary>
|
||
public class XAuthorizationCache : IXAuthorizationCache
|
||
{
|
||
private readonly TimeSpan ttl;
|
||
private readonly IMemoryCache cache;
|
||
private readonly ConcurrentDictionary<string, byte> keys = new ConcurrentDictionary<string, byte>();
|
||
|
||
public XAuthorizationCache(IMemoryCache cache)
|
||
{
|
||
this.cache = cache;
|
||
this.ttl = TimeSpan.FromMinutes(XAuthorizationServiceConstants.DefaultCacheTtlMinutes);
|
||
}
|
||
|
||
public bool TryGetPolicy(string name, out AuthorizationPolicy policy)
|
||
{
|
||
policy = null;
|
||
return !name.IsNullOrEmpty() && cache.TryGetValue(Key(name), out policy);
|
||
}
|
||
|
||
public void SetPolicy(string name, AuthorizationPolicy policy)
|
||
{
|
||
//
|
||
if (name.IsNullOrEmpty() || policy.IsNull())
|
||
{
|
||
return;
|
||
}
|
||
|
||
//
|
||
cache.Set(Key(name), policy, ttl);
|
||
keys[Key(name)] = 0;
|
||
}
|
||
|
||
public void RemovePolicy(string name)
|
||
{
|
||
cache.Remove(Key(name));
|
||
keys.TryRemove(Key(name), out _);
|
||
}
|
||
|
||
public void Clear()
|
||
{
|
||
foreach (var key in keys.Keys)
|
||
{
|
||
cache.Remove(key);
|
||
}
|
||
keys.Clear();
|
||
}
|
||
|
||
//
|
||
#region Private ...
|
||
private static string Key(string name) =>
|
||
XAuthorizationServiceConstants.PolicyCacheKeyPrefix + name.ToNormalString();
|
||
#endregion
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">Providers/XDynamicPolicyProvider.cs</span><pre>using xCommons.Extensions;
|
||
using System.Threading.Tasks;
|
||
using Microsoft.Extensions.Options;
|
||
using xAuthorizationService.Interfaces;
|
||
using xAuthorizationService.Extensions;
|
||
using Microsoft.AspNetCore.Authorization;
|
||
using Microsoft.Extensions.DependencyInjection;
|
||
using xAuthorizationService.Interfaces.Entities;
|
||
|
||
namespace xAuthorizationService.Providers
|
||
{
|
||
/// <summary>
|
||
/// Resolve Policies from Cache → Repository → Default (static) Provider ...
|
||
/// </summary>
|
||
public class XDynamicPolicyProvider : IAuthorizationPolicyProvider
|
||
{
|
||
private readonly IXAuthorizationCache cache;
|
||
private readonly IServiceScopeFactory scopeFactory;
|
||
private readonly DefaultAuthorizationPolicyProvider fallback;
|
||
|
||
public XDynamicPolicyProvider(
|
||
IXAuthorizationCache cache,
|
||
IServiceScopeFactory scopeFactory,
|
||
IOptions<AuthorizationOptions> options
|
||
)
|
||
{
|
||
this.cache = cache;
|
||
this.scopeFactory = scopeFactory;
|
||
this.fallback = new DefaultAuthorizationPolicyProvider(options);
|
||
}
|
||
|
||
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => fallback.GetDefaultPolicyAsync();
|
||
|
||
public Task<AuthorizationPolicy> GetFallbackPolicyAsync() => fallback.GetFallbackPolicyAsync();
|
||
|
||
public async Task<AuthorizationPolicy> 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<IXPolicyDefinitionRepository>();
|
||
var resolver = scope.ServiceProvider.GetService<IXRoleHierarchyResolver>();
|
||
|
||
//
|
||
if (!repository.IsNull() && !resolver.IsNull())
|
||
{
|
||
//
|
||
var normalized = policyName.ToNormalString();
|
||
var definition = await repository.FindOneAsync(
|
||
predicate: p => p.IsEnabled && p.Name.ToLower() == normalized
|
||
);
|
||
|
||
//
|
||
if (!definition.IsNull())
|
||
{
|
||
//
|
||
var roles = await resolver.ResolveEffectiveRolesAsync(
|
||
explicitRoles: definition.RequiredRoles.ToCsvList(),
|
||
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);
|
||
}
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="warning-box">
|
||
<strong>ترتیب اولویت:</strong> Policy پویا بر Policy ایستای همنام اولویت دارد. این عمداً است تا پس از Seed (گام ۸) بتوان Policyهای <code>XPolicies.*</code> را از طریق API تغییر داد، درحالیکه اگر رکورد DB حذف/غیرفعال شود، بهطور خودکار به تعریف کد برمیگردیم. <code>LocalApi.PolicyName</code> هرگز Seed نمیشود و همیشه از Fallback میآید.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۸ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۸</div>
|
||
<div class="section-title">
|
||
<h3>گام ۸ — XAuthorizationProvider (Facade)، قراردادهای Sync و Seeder</h3>
|
||
<div class="subtitle">Step 8: Provider Facade, Sync Contracts & Seeder</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p class="no-indent">Provider بهصورت <code>partial</code> (مثل <code>XApplicationProvider</code>) نوشته میشود. تنها قسمتهای وابسته به IdentityServer4/ASP.NET Identity پشت دو اینترفیس Sync پنهاناند تا ماژول <code>netstandard2.0</code> بماند و پیادهسازی در xIds انجام شود (گام ۹).</p>
|
||
|
||
<div class="code-box"><span class="file">Interfaces/IXScopeSyncService.cs + IXRoleSyncService.cs</span><pre>using 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);
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Interfaces/IXAuthorizationProvider.cs</span><pre>using 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
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">Providers/XAuthorizationProvider.cs (Core — partial)</span><pre>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) { }
|
||
}
|
||
}
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">Providers/XAuthorizationProvider+Policy.cs (الگو برای +Scope و +Role)</span><pre>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
|
||
}
|
||
}</pre></div>
|
||
<h4>Seeder — انتقال ثابتهای فعلی به DB با <code>IsSystem = true</code></h4>
|
||
<p class="no-indent"><code>XBaseDbSeeder</code> فریمورک از <code>appsettings:XDataService.Databases[db].SeedItems[entity]</code> میخواند. برای ثابتهای کد (که نباید در appsettings تکرار شوند) یک Seeder کدمحور مینویسیم که در <code>UseXAuthorizationService</code> پس از <code>UseXRepository</code> فراخوانی میشود (همان الگوی <code>XDbSeeder.SeedData</code> در xIds):</p>
|
||
|
||
<div class="code-box"><span class="file">Providers/XAuthorizationSeeder.cs</span><pre>using 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
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">DI/XDIHelperExtension.cs — افزودن به انتهای UseXAuthorizationService</span><pre> //
|
||
// 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();
|
||
}</pre></div>
|
||
|
||
<div class="success-box">
|
||
<strong>نتیجهی گام ۸:</strong> پس از اولین اجرا، DB شامل ۴ Scope، ۱۱ Role (با Weight) و ۳۰ Policy با <code>IsSystem = true</code> است که ۱:۱ با <code>XAuthorizationHelper</code> معادلاند. Seeder idempotent است و در اجراهای بعدی فقط رکوردهای غایب را اضافه میکند؛ بنابراین ویرایشهای ادمین روی رکوردهای موجود حفظ میشود.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۹ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۹</div>
|
||
<div class="section-title">
|
||
<h3>گام ۹ — یکپارچهسازی با xIds (DbContext، Sync Services، Startup)</h3>
|
||
<div class="subtitle">Step 9: xIds Integration</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<div class="warning-box">
|
||
<strong>نکتهی مهم:</strong> <code>XIdentityDbContext</code> از <code>IdentityDbContext</code> ارث میبرد و <code>XDbContext</code> نیست؛ بنابراین نمیتواند مستقیم به <code>AddXAuthorizationService<TContext></code> داده شود. راهحل مطابق فریمورک: یک <strong>DbContext چهارم</strong> در xIds (<code>XAuthorizationDbContext : XDbContext</code>) با ConnectionString جداگانه <code>AuthorizationDb</code>، دقیقاً مانند <code>XAiApiDbContext</code> در xAiApi.
|
||
</div>
|
||
|
||
<div class="code-box"><span class="file">xIds/appsettings.json — افزودن</span><pre>"ConnectionStrings": {
|
||
"IdentityDb": "Filename=./Db/XIdentity.db;Foreign Keys=False",
|
||
"ConfigurationDb": "Filename=./Db/XConfigurations.db",
|
||
"PersistedGrantDb": "Filename=./Db/XPersistedGrants.db",
|
||
"AuthorizationDb": "Filename=./Db/XAuthorization.db"
|
||
},
|
||
"DataServiceConfiguration": {
|
||
"Databases": {
|
||
"xAuthorizationDb": {
|
||
"Provider": "SQLITE",
|
||
"ConnectionString": "Filename=./Db/XAuthorization.db",
|
||
"SeedItems": {}
|
||
}
|
||
},
|
||
"SeedingMode": "AddIfNotExists",
|
||
"EnableTracking": true,
|
||
"PagingConfiguration": { "DefaultPageSize": 20, "MaxAvailablePageSize": 400, "MinAvailablePageSize": 5 },
|
||
"GraphQLBasePath": "/graphs"
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">xIds/DbContext/XAuthorizationDbContext.cs + XAuthorizationDatabaseDescriptor.cs</span><pre>using xDataService.Db;
|
||
using xDataService.Providers;
|
||
using xDataService.Configuration;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using xAuthorizationService.Providers;
|
||
|
||
namespace xIds.DbContext
|
||
{
|
||
/// <summary>
|
||
/// Db Context of Dynamic Authorization Definitions ...
|
||
/// </summary>
|
||
public class XAuthorizationDbContext : XDbContext
|
||
{
|
||
public XAuthorizationDbContext(
|
||
DbContextOptions options,
|
||
XDataServiceConfiguration config,
|
||
XEntityRegisterarHandlerService dynamicEntityHandlers
|
||
) : base(
|
||
config: config,
|
||
options: options,
|
||
database: XDataServiceConstants.XAuthorizationDbIdentifier, // "xAuthorizationDb"
|
||
dynamicEntityHandlers: dynamicEntityHandlers,
|
||
dynamicEntityRegisterarsNames: [
|
||
nameof(XAuthorizationEntityRegisterar)
|
||
]
|
||
)
|
||
{ }
|
||
|
||
public override void OnXModelCreating(ModelBuilder modelBuilder) { }
|
||
public override void OnXConfiguring(DbContextOptionsBuilder optionsBuilder) { }
|
||
}
|
||
}
|
||
|
||
// ----- XAuthorizationDatabaseDescriptor.cs -----
|
||
using xDataService.Models;
|
||
using xDataService.Interfaces;
|
||
|
||
namespace xIds.DbContext
|
||
{
|
||
public class XAuthorizationDatabaseDescriptor
|
||
: XDatabaseDescriptor<XAuthorizationDbContext>, IXDatabaseDescriptor<XAuthorizationDbContext>
|
||
{
|
||
public XAuthorizationDatabaseDescriptor() : base(
|
||
name: XDataServiceConstants.XAuthorizationDbIdentifier,
|
||
repositories: []
|
||
)
|
||
{
|
||
OptionsBuilder = b => b.MigrationsAssembly("xIds");
|
||
}
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">xIds/Providers/Authorization/XIdentityServerScopeSyncService.cs</span><pre>using System.Linq;
|
||
using System.Threading;
|
||
using xCommons.Extensions;
|
||
using System.Threading.Tasks;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using xAuthorizationService.Interfaces;
|
||
using xAuthorizationService.Extensions;
|
||
using xAuthorizationService.Models.Entities;
|
||
using IdentityServer4.EntityFramework.Entities;
|
||
using IdentityServer4.EntityFramework.DbContexts;
|
||
|
||
namespace xIds.Providers.Authorization
|
||
{
|
||
/// <summary>
|
||
/// Mirror XScopeDefinition into IdentityServer4 ApiScopes ...
|
||
/// </summary>
|
||
public class XIdentityServerScopeSyncService : IXScopeSyncService
|
||
{
|
||
private readonly ConfigurationDbContext configDb;
|
||
|
||
public XIdentityServerScopeSyncService(ConfigurationDbContext configDb)
|
||
{
|
||
this.configDb = configDb;
|
||
}
|
||
|
||
public async Task UpsertAsync(XScopeDefinition scope, CancellationToken cancellationToken = default)
|
||
{
|
||
//
|
||
var exists = await configDb.ApiScopes
|
||
.Include(s => s.UserClaims)
|
||
.FirstOrDefaultAsync(s => s.Name == scope.Name, cancellationToken);
|
||
|
||
//
|
||
if (exists.IsNull())
|
||
{
|
||
exists = new ApiScope { Name = scope.Name };
|
||
configDb.ApiScopes.Add(exists);
|
||
}
|
||
|
||
//
|
||
exists.Enabled = scope.IsEnabled;
|
||
exists.DisplayName = scope.DisplayName;
|
||
exists.Description = scope.Description;
|
||
exists.UserClaims = scope.UserClaims.ToCsvList()
|
||
.Select(c => new ApiScopeClaim { Type = c })
|
||
.ToList();
|
||
|
||
//
|
||
await configDb.SaveChangesAsync(cancellationToken);
|
||
}
|
||
|
||
public async Task RemoveAsync(string scopeName, CancellationToken cancellationToken = default)
|
||
{
|
||
//
|
||
var exists = await configDb.ApiScopes
|
||
.FirstOrDefaultAsync(s => s.Name == scopeName, cancellationToken);
|
||
if (!exists.IsNull())
|
||
{
|
||
configDb.ApiScopes.Remove(exists);
|
||
await configDb.SaveChangesAsync(cancellationToken);
|
||
}
|
||
}
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">xIds/Providers/Authorization/XAspNetIdentityRoleSyncService.cs</span><pre>using System.Linq;
|
||
using xIds.Interfaces;
|
||
using System.Threading;
|
||
using xCommons.Extensions;
|
||
using System.Threading.Tasks;
|
||
using System.Collections.Generic;
|
||
using Microsoft.AspNetCore.Identity;
|
||
using xAuthorizationService.Interfaces;
|
||
using xAuthorizationService.Models.Entities;
|
||
|
||
namespace xIds.Providers.Authorization
|
||
{
|
||
/// <summary>
|
||
/// Mirror XRoleDefinition into ASP.NET IdentityRole (reuses XIdentityManager) ...
|
||
/// </summary>
|
||
public class XAspNetIdentityRoleSyncService : IXRoleSyncService
|
||
{
|
||
private readonly IXIdentityManager identityManager;
|
||
private readonly RoleManager<IdentityRole> roleManager;
|
||
private readonly UserManager<xIdentityModels.Models.XUser> userManager;
|
||
|
||
public XAspNetIdentityRoleSyncService(
|
||
IXIdentityManager identityManager,
|
||
RoleManager<IdentityRole> roleManager,
|
||
UserManager<xIdentityModels.Models.XUser> userManager
|
||
)
|
||
{
|
||
this.roleManager = roleManager;
|
||
this.userManager = userManager;
|
||
this.identityManager = identityManager;
|
||
}
|
||
|
||
public async Task UpsertAsync(XRoleDefinition role, CancellationToken cancellationToken = default)
|
||
{
|
||
//
|
||
var isExists = await identityManager.IsRoleExistsAsync(role.Name);
|
||
if (!isExists)
|
||
{
|
||
await identityManager.CreateRoleAsync(role.Name);
|
||
}
|
||
}
|
||
|
||
public async Task RemoveAsync(string roleName, CancellationToken cancellationToken = default)
|
||
{
|
||
//
|
||
var role = await roleManager.FindByNameAsync(roleName);
|
||
if (!role.IsNull())
|
||
{
|
||
await roleManager.DeleteAsync(role);
|
||
}
|
||
}
|
||
|
||
public async Task<int> CountUsersInRoleAsync(string roleName, CancellationToken cancellationToken = default)
|
||
{
|
||
var users = await userManager.GetUsersInRoleAsync(roleName);
|
||
return users.Count;
|
||
}
|
||
|
||
public async Task<IEnumerable<string>> GetUserRolesAsync(string userSelectByParam, CancellationToken cancellationToken = default)
|
||
{
|
||
return await identityManager.GetRoleNamesAsync(userSelectByParam, checkCanLoginPolicies: false, checkIsBanned: false);
|
||
}
|
||
}
|
||
}</pre></div>
|
||
<div class="code-box"><span class="file">xIds/Startup.cs — تغییرات (ترتیب مهم است)</span><pre>// usings ...
|
||
using xDataService.DI;
|
||
using xDataService.Models;
|
||
using xAuthorizationService.DI;
|
||
using xAuthorizationService.Interfaces;
|
||
using xIds.Providers.Authorization;
|
||
|
||
public class Startup
|
||
{
|
||
private readonly List<XDatabaseDescriptor> databases;
|
||
|
||
public Startup(IConfiguration configuration)
|
||
{
|
||
Configuration = configuration;
|
||
|
||
//
|
||
// Authorization Database Descriptor (same as xAiApi) ...
|
||
databases = new List<XDatabaseDescriptor>
|
||
{
|
||
new XAuthorizationDatabaseDescriptor()
|
||
};
|
||
}
|
||
|
||
public void ConfigureServices(IServiceCollection services)
|
||
{
|
||
// ... AddXCommons / AddXAppConfiguration / AddXLoggingService ... (unchanged)
|
||
|
||
//
|
||
// Register IdentityServer to DI ...
|
||
services.AddEfSupportXIdentityServer(Configuration);
|
||
services.AddXApplicationProvider(Configuration);
|
||
|
||
//
|
||
// Push Service (required for Entity Hubs) ...
|
||
services.AddXPushService(
|
||
lifeTime: ServiceLifetime.Scoped,
|
||
config: Configuration
|
||
);
|
||
|
||
//
|
||
// Register Authorization Database ...
|
||
databases.ForEach(database =>
|
||
{
|
||
services.AddXDatabase(
|
||
lifeTime: ServiceLifetime.Scoped,
|
||
descriptor: database,
|
||
configuration: Configuration
|
||
);
|
||
});
|
||
|
||
//
|
||
// Register Dynamic Authorization Service ...
|
||
services.AddXAuthorizationService<XAuthorizationDbContext>(
|
||
lifeTime: ServiceLifetime.Scoped,
|
||
repositoryType: XRepositoryType.EF
|
||
);
|
||
|
||
//
|
||
// xIds-only Sync Implementations ...
|
||
services.AddScoped<IXScopeSyncService, XIdentityServerScopeSyncService>();
|
||
services.AddScoped<IXRoleSyncService, XAspNetIdentityRoleSyncService>();
|
||
|
||
//
|
||
services.AddControllers()
|
||
.AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
|
||
|
||
//
|
||
// Register Authentication ...
|
||
services.AddXIdentityServerAuthentication(Configuration);
|
||
|
||
//
|
||
// Register Authorization (static policies remain as fallback) ...
|
||
services.AddXAuthorization();
|
||
|
||
//
|
||
// Replace IAuthorizationPolicyProvider — MUST be after AddXAuthorization ...
|
||
services.AddXDynamicPolicyProvider();
|
||
|
||
//
|
||
services.AddSingleton<IXSecurityProvider, XSecurityProvider>();
|
||
}
|
||
|
||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
|
||
{
|
||
// ... UseXSwagger / UseHttpsRedirection / UseXCors ... (unchanged)
|
||
|
||
//
|
||
app.UseXIdentityServer(logger);
|
||
app.UseXStorageService();
|
||
|
||
//
|
||
// Authorization Database + Service (Hubs, Repositories, Seeder) ...
|
||
databases.ForEach(database =>
|
||
{
|
||
app.UseXDatabase(
|
||
descriptor: database,
|
||
isDevelopmentEnvironment: isDevelopmentEnvironment
|
||
);
|
||
});
|
||
app.UseXAuthorizationService(isDevelopmentEnvironment);
|
||
|
||
//
|
||
app.UseRouting();
|
||
app.UseAuthentication();
|
||
app.UseAuthorization();
|
||
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">PowerShell — Migration برای DbContext جدید</span><pre>cd xIds
|
||
dotnet ef migrations add InitAuthorization --context XAuthorizationDbContext --output-dir Migrations/Authorization
|
||
dotnet ef database update --context XAuthorizationDbContext</pre></div>
|
||
|
||
<div class="info-box">
|
||
<strong>چرا ترتیب <code>AddXAuthorization()</code> → <code>AddXDynamicPolicyProvider()</code>؟</strong> <code>AddXAuthorization</code> در <code>xIds/DI</code> داخل <code>AddAuthorization(options => …)</code> همهی Policyهای ایستا را به <code>AuthorizationOptions</code> اضافه میکند. <code>XDynamicPolicyProvider</code> همان <code>IOptions<AuthorizationOptions></code> را به <code>DefaultAuthorizationPolicyProvider</code> داخلی میدهد؛ بنابراین Fallback دقیقاً همان Policyهای امروز را میبیند. ثبت <code>AddSingleton<IAuthorizationPolicyProvider></code> بعد از آن، ثبت پیشفرض ASP.NET را override میکند.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۱۰ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۱۰</div>
|
||
<div class="section-title">
|
||
<h3>گام ۱۰ — AuthorizationController در xIds (۴ partial)</h3>
|
||
<div class="subtitle">Step 10: Admin API Controller</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p class="no-indent">کنترلر دقیقاً با الگوی <code>ApplicationsController</code> نوشته میشود: فایل اصلی + <code>+Scope.cs</code>، <code>+Role.cs</code>، <code>+Policy.cs</code>، <code>+Utility.cs</code>. همهی اکشنها با سه Attribute محافظت میشوند.</p>
|
||
|
||
<div class="code-box"><span class="file">xIds/Controllers/AuthorizationController.cs</span><pre>using xIds.Interfaces;
|
||
using xCommons.Providers;
|
||
using xIds.Controllers.Base;
|
||
using xCommons.Configurations;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
using Microsoft.Extensions.Logging;
|
||
using xAuthorizationService.Interfaces;
|
||
|
||
namespace xIds.Controllers
|
||
{
|
||
/// <summary>
|
||
/// Provide all available tools for managing Scopes, Roles and Policies dynamically ...
|
||
/// </summary>
|
||
[ApiController]
|
||
[Route("authorization")]
|
||
public partial class AuthorizationController : XIBaseController
|
||
{
|
||
private readonly IXAuthorizationProvider provider;
|
||
|
||
public AuthorizationController(
|
||
IXAuthorizationProvider provider,
|
||
IXIdentityManager identityManager,
|
||
XAppConfiguration appConfiguration,
|
||
ILogger<AuthorizationController> logger,
|
||
XValidationProvider validationProvider
|
||
) : base(
|
||
logger,
|
||
appConfiguration,
|
||
identityManager,
|
||
validationProvider
|
||
)
|
||
{
|
||
this.provider = provider;
|
||
}
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">xIds/Controllers/Authorization/AuthorizationController+Policy.cs</span><pre>using System;
|
||
using xModels.Dtos;
|
||
using xIdentityHelper;
|
||
using System.Threading;
|
||
using xCommons.Attributes;
|
||
using xCommons.Extensions;
|
||
using xExceptions.Constants;
|
||
using System.Threading.Tasks;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
using xAuthorizationService.Models.Dtos;
|
||
using Microsoft.AspNetCore.Authorization;
|
||
using static IdentityServer4.IdentityServerConstants;
|
||
|
||
namespace xIds.Controllers
|
||
{
|
||
public partial class AuthorizationController
|
||
{
|
||
//
|
||
#region Policy ...
|
||
/// <summary>
|
||
/// Query Policies ...
|
||
/// </summary>
|
||
[HttpGet("policies")]
|
||
[RequireXPowered]
|
||
[Authorize(LocalApi.PolicyName)]
|
||
[Authorize(Policy = XPolicies.EnabledAdmin)]
|
||
public async Task<ActionResult<XQueryResult<XPolicyDefinitionDto>>> QueryPolicies(
|
||
[FromQuery] XQuery query,
|
||
CancellationToken cancellationToken = default
|
||
)
|
||
{
|
||
//
|
||
try
|
||
{
|
||
//
|
||
var result = await provider.QueryPoliciesAsync(
|
||
query: query,
|
||
cancellationToken: cancellationToken
|
||
);
|
||
|
||
//
|
||
return Ok(result);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
//
|
||
var result = GetExceptionActionResult(ex);
|
||
return result;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Create Policy ...
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// Sample request:
|
||
///
|
||
/// {
|
||
/// "name": "enabledEditorPolicy",
|
||
/// "displayName": "ویراستار فعال",
|
||
/// "kind": 0,
|
||
/// "minRoleWeight": 4,
|
||
/// "requiredScopes": ["XAPI.write"],
|
||
/// "requireEnabledUser": true
|
||
/// }
|
||
///
|
||
/// </remarks>
|
||
[HttpPost("policies")]
|
||
[RequireXPowered]
|
||
[Authorize(LocalApi.PolicyName)]
|
||
[Authorize(Policy = XPolicies.EnabledAdmin)]
|
||
public async Task<ActionResult<XPolicyDefinitionDto>> CreatePolicy(
|
||
[FromBody] XPolicyDefinitionDto item,
|
||
CancellationToken cancellationToken = default
|
||
)
|
||
{
|
||
//
|
||
try
|
||
{
|
||
//
|
||
// Validate ...
|
||
if (item.IsNull() || item.Name.IsNullOrEmpty())
|
||
{
|
||
XException.InvalidArgs.Throw();
|
||
}
|
||
|
||
//
|
||
var userInfo = await GetUserInfo();
|
||
|
||
//
|
||
var result = await provider.AddPolicyAsync(
|
||
item: item,
|
||
userInfo: userInfo,
|
||
cancellationToken: cancellationToken
|
||
);
|
||
|
||
//
|
||
return Ok(result.ToDynamicObject());
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
//
|
||
var result = GetExceptionActionResult(ex);
|
||
return result;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Evaluate Policy against a User (dry-run for Admin UI) ...
|
||
/// </summary>
|
||
[HttpPost("policies/{name}/evaluate")]
|
||
[RequireXPowered]
|
||
[Authorize(LocalApi.PolicyName)]
|
||
[Authorize(Policy = XPolicies.EnabledAdmin)]
|
||
public async Task<ActionResult<XPolicyEvaluationResultDto>> EvaluatePolicy(
|
||
[FromRoute] string name,
|
||
[FromBody] XActionRequest model,
|
||
CancellationToken cancellationToken = default
|
||
)
|
||
{
|
||
//
|
||
try
|
||
{
|
||
//
|
||
var userSelectByParam = GetUserSelectByParam(model);
|
||
var user = await IdentityManager.GetUserAsync(userSelectByParam);
|
||
var claims = await IdentityManager.ToJwtClaims(user, checkCanLoginPolicies: false, checkIsBanned: false);
|
||
var target = new XUserClaimsInfoDto(accessToken: null, refreshToken: null, expiresAt: null, claims: claims);
|
||
|
||
//
|
||
var result = await provider.EvaluatePolicyAsync(
|
||
name: name,
|
||
target: target,
|
||
cancellationToken: cancellationToken
|
||
);
|
||
|
||
//
|
||
return Ok(result);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
//
|
||
var result = GetExceptionActionResult(ex);
|
||
return result;
|
||
}
|
||
}
|
||
|
||
// GET policies/{name}, PUT policies/{name}, DELETE policies/{name} → same pattern ...
|
||
#endregion
|
||
}
|
||
}</pre></div>
|
||
|
||
<table class="styled-table">
|
||
<thead><tr><th>Partial</th><th>Routeها</th><th>قاعدهی ویژه</th></tr></thead>
|
||
<tbody>
|
||
<tr><td><code>+Scope.cs</code></td><td>GET/POST <code>scopes</code>، GET/PUT/DELETE <code>scopes/{name}</code></td><td>پس از Add/Update → <code>IXScopeSyncService.UpsertAsync</code>؛ DELETE روی <code>IsSystem</code> → <code>XException.NotAllowed</code></td></tr>
|
||
<tr><td><code>+Role.cs</code></td><td>GET/POST <code>roles</code>، GET/PUT/DELETE <code>roles/{name}</code>، GET <code>roles/{name}/users</code></td><td>DELETE فقط اگر <code>CountUsersInRoleAsync == 0</code>؛ نقش <code>admin</code> همیشه <code>IsSystem</code></td></tr>
|
||
<tr><td><code>+Policy.cs</code></td><td>GET/POST <code>policies</code>، GET/PUT/DELETE <code>policies/{name}</code>، POST <code>policies/{name}/evaluate</code></td><td>PUT/DELETE روی <code>IsSystem</code> فقط تغییر <code>DisplayName</code>/<code>IsEnabled</code> مجاز است</td></tr>
|
||
<tr><td><code>+Utility.cs</code></td><td>POST <code>sync</code>، GET <code>effective/{userSelectByParam}</code></td><td><code>sync</code> = <code>SyncAllAsync</code> (DB → IdentityServer + RoleManager) + <code>InvalidateAsync()</code></td></tr>
|
||
</tbody>
|
||
</table>
|
||
|
||
<div class="success-box">
|
||
<strong>تست دستی گام ۱۰ (Swagger):</strong> ۱) ورود با ادمین و دریافت Local API token؛ ۲) <code>POST /authorization/policies</code> با نمونهی بالا؛ ۳) در همان لحظه، اکشنی با <code>[Authorize(Policy = "enabledEditorPolicy")]</code> در xIds برای کاربر <code>actuary_assistant</code> باید 200 و برای <code>agent</code> باید 403 بدهد — بدون restart.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۱۱ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۱۱</div>
|
||
<div class="section-title">
|
||
<h3>گام ۱۱ — اصلاح Handlerها و گسترش به سرویسهای مصرفکننده</h3>
|
||
<div class="subtitle">Step 11: RequiredRolesHandler Fix, XPolicyHandler, Consumers & Event Invalidation</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<h4>۱۱.۱ اصلاح <code>RequiredRolesHandler</code> (بررسی همهی Claimهای role)</h4>
|
||
<div class="code-box"><span class="file">Modules/xCommons/Authorization/RequiredRolesHandler.cs</span><pre>using System;
|
||
using System.Linq;
|
||
using IdentityModel;
|
||
using System.Threading.Tasks;
|
||
using Microsoft.AspNetCore.Authorization;
|
||
|
||
namespace xCommons.Authorization {
|
||
public partial class RequiredRolesHandler : AuthorizationHandler<RequiredRolesRequirement> {
|
||
protected override Task HandleRequirementAsync (
|
||
AuthorizationHandlerContext context,
|
||
RequiredRolesRequirement requirement
|
||
) {
|
||
//
|
||
// Collect ALL role claims (user may have multiple roles) ...
|
||
var userRoles = context.User.Claims
|
||
.Where (c => c.Type == JwtClaimTypes.Role)
|
||
.Select (c => c.Value)
|
||
.ToList ();
|
||
if (userRoles.Count == 0) {
|
||
return Task.CompletedTask;
|
||
}
|
||
|
||
//
|
||
var isMatched = requirement.Roles.Any (required =>
|
||
userRoles.Any (r => string.Equals (r, required, StringComparison.InvariantCultureIgnoreCase)));
|
||
if (!isMatched) {
|
||
return Task.CompletedTask;
|
||
}
|
||
|
||
//
|
||
context.Succeed (requirement);
|
||
return Task.CompletedTask;
|
||
}
|
||
}
|
||
}</pre></div>
|
||
|
||
<h4>۱۱.۲ بازنویسی <code>XPolicyHandler</code> (حذف static Dictionary)</h4>
|
||
<p class="no-indent"><code>IXPolicyHandler.IsPolicyPassed(policy, roles)</code> در کد موجود برای بررسیهای programmatic استفاده میشود. پیادهسازی جدید بهجای Dictionary ایستا، از <code>IAuthorizationPolicyProvider</code> (که اکنون پویاست) <code>RequiredRolesRequirement</code> را استخراج میکند؛ بنابراین هیچ تغییری در فراخوانیهای موجود لازم نیست:</p>
|
||
|
||
<div class="code-box"><span class="file">Modules/xIdentityService/Providers/XPolicyHandler.cs</span><pre>using System;
|
||
using System.Linq;
|
||
using xCommons.Extensions;
|
||
using xExceptions.Constants;
|
||
using xCommons.Authorization;
|
||
using System.Collections.Generic;
|
||
using xIdentityService.Interfaces;
|
||
using System.Collections.Concurrent;
|
||
using Microsoft.AspNetCore.Authorization;
|
||
|
||
namespace xIdentityService.Providers
|
||
{
|
||
public class XPolicyHandler : IXPolicyHandler
|
||
{
|
||
//
|
||
// Thread-safe, instance-scoped (registered as Singleton by AddXIdentityService) ...
|
||
private readonly ConcurrentDictionary<string, IEnumerable<string>> policies =
|
||
new ConcurrentDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
|
||
private readonly IAuthorizationPolicyProvider policyProvider;
|
||
|
||
public XPolicyHandler(IAuthorizationPolicyProvider policyProvider = null)
|
||
{
|
||
this.policyProvider = policyProvider;
|
||
}
|
||
|
||
public bool AddPolicy(string policy, IEnumerable<string> requiredRoles)
|
||
{
|
||
//
|
||
if (policy.IsNullOrEmpty() || !requiredRoles.HasChild())
|
||
{
|
||
XException.InvalidArgs.Throw();
|
||
}
|
||
|
||
//
|
||
return policies.TryAdd(policy.ToNormalString(), requiredRoles.Select(r => r.ToNormalString()).ToList());
|
||
}
|
||
|
||
public bool HasPolicy(string policy) =>
|
||
!policy.IsNullOrEmpty() && (policies.ContainsKey(policy) || ResolveRoles(policy).HasChild());
|
||
|
||
public bool RemovePolicy(string policy) =>
|
||
!policy.IsNullOrEmpty() && policies.TryRemove(policy, out _);
|
||
|
||
public bool IsPolicyPassed(string policy, IEnumerable<string> roles)
|
||
{
|
||
//
|
||
if (!roles.HasChild() || policy.IsNullOrEmpty())
|
||
{
|
||
XException.InvalidArgs.Throw();
|
||
}
|
||
|
||
//
|
||
var requiredRoles = ResolveRoles(policy);
|
||
return requiredRoles.HasChild() &&
|
||
roles.Any(r => requiredRoles.Any(rq => r.Equals(rq, StringComparison.InvariantCultureIgnoreCase)));
|
||
}
|
||
|
||
//
|
||
#region Private ...
|
||
/// <summary>
|
||
/// Dynamic first (IAuthorizationPolicyProvider), then local registry ...
|
||
/// </summary>
|
||
private IEnumerable<string> ResolveRoles(string policy)
|
||
{
|
||
//
|
||
if (!policyProvider.IsNull())
|
||
{
|
||
//
|
||
var resolved = policyProvider.GetPolicyAsync(policy).GetAwaiter().GetResult();
|
||
var requirement = resolved?.Requirements.OfType<RequiredRolesRequirement>().FirstOrDefault();
|
||
if (!requirement.IsNull() && requirement.Roles.HasChild())
|
||
{
|
||
return requirement.Roles.Select(r => r.ToNormalString()).ToList();
|
||
}
|
||
}
|
||
|
||
//
|
||
return policies.TryGetValue(policy.ToNormalString(), out var local) ? local : null;
|
||
}
|
||
#endregion
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="warning-box">
|
||
<strong>توجه به معناشناسی:</strong> <code>IsPolicyPassed</code> فعلی با <code>roles.All(...)</code> کار میکند (همهی نقشهای کاربر باید در لیست مجاز باشند). نسخهی بالا به <code>Any</code> تغییر کرده تا با <code>RequiredRolesHandler</code> اصلاحشده (و منطق کاربر چندنقشه) همخوان باشد. اگر جایی به رفتار <code>All</code> وابسته است، آن را در Code Review بررسی کنید.
|
||
</div>
|
||
|
||
<h4>۱۱.۳ گسترش به مصرفکنندهها (xApi / xAiApi / xAiMcpServer)</h4>
|
||
<p class="no-indent">سرویسهای مصرفکننده به DB مجوزها دسترسی مستقیم ندارند. دو گزینه وجود دارد؛ گزینهی A برای شروع کافی و بدون وابستگی جدید است:</p>
|
||
|
||
<table class="styled-table">
|
||
<thead><tr><th>گزینه</th><th>روش</th><th>مزیت / هزینه</th></tr></thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><strong>A — Remote Policy Provider</strong> (پیشنهادی)</td>
|
||
<td><code>XRemotePolicyProvider : IAuthorizationPolicyProvider</code> در <code>xIdentityService</code> که با <code>IXIdentityHttpProvider</code> از <code>GET {xIds}/authorization/policies/{name}</code> تعریف را میگیرد و با <code>ToAuthorizationPolicy()</code> میسازد + <code>IXAuthorizationCache</code> با TTL</td>
|
||
<td>بدون DbContext جدید در مصرفکنندهها؛ یک Endpoint read-only با <code>XPolicies.ReadAccess</code> (Scope) کافی است. هزینه: یک HTTP call در cache-miss</td>
|
||
</tr>
|
||
<tr>
|
||
<td><strong>B — Shared Database</strong></td>
|
||
<td>همان <code>AddXAuthorizationService<XApiDbContext>(XRepositoryType.EF)</code> با ConnectionString مشترک به <code>AuthorizationDb</code></td>
|
||
<td>بدون HTTP؛ اما Coupling روی Schema و نیاز به دسترسی شبکهای به DB هویت</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
|
||
<div class="code-box"><span class="file">Modules/xIdentityService/Constants/XApiAccountEndpoint.cs — افزودن</span><pre>//
|
||
// Authorization (Dynamic Policies) ...
|
||
public const string AuthorizationPolicy = "authorization/policies/{0}";
|
||
public const string AuthorizationEffective = "authorization/effective/{0}";</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Modules/xIdentityService/DI/XDIHelperExtension.cs — افزودن</span><pre>/// <summary>
|
||
/// Register Remote Dynamic Policy Provider (Consumers) ...
|
||
/// </summary>
|
||
public static void AddXRemotePolicyProvider(this IServiceCollection services)
|
||
{
|
||
//
|
||
services.AddMemoryCache();
|
||
services.AddSingleton<IXAuthorizationCache, XAuthorizationCache>();
|
||
services.AddSingleton<IAuthorizationPolicyProvider, XRemotePolicyProvider>();
|
||
}
|
||
|
||
// xAiApi/Startup.cs:
|
||
services.AddXAuthorization(); // static fallback
|
||
services.AddXRemotePolicyProvider(); // after AddXAuthorization</pre></div>
|
||
|
||
<h4>۱۱.۴ Invalidation رویدادمحور</h4>
|
||
<p class="no-indent"><code>xEventService</code> در وضعیت فعلی فقط قرارداد Producer (<code>IXProducerServiceBase.SendMessageAsync</code>) دارد و Consumer استانداردی در فریمورک تعریف نشده است. بنابراین استراتژی invalidation دو لایه است:</p>
|
||
<ul class="plain">
|
||
<li><strong>لایهی ۱ (همیشه فعال):</strong> TTL پنجدقیقهای <code>XAuthorizationCache</code> — حداکثر تأخیر انتشار تغییر = ۵ دقیقه.</li>
|
||
<li><strong>لایهی ۲ (اختیاری):</strong> <code>XAuthorizationProvider.InvalidateAsync</code> رویداد <code>authorization.changed</code> را روی Topic همنام منتشر میکند. هر مصرفکننده میتواند یک <code>BackgroundService</code> (<code>XAuthorizationChangedListener</code>) ثبت کند که با Kafka/RabbitMQ consumer به آن Topic گوش داده و <code>IXAuthorizationCache.Clear()</code> را صدا بزند. این بخش پس از افزودن قرارداد Consumer به xEventService تکمیل میشود.</li>
|
||
<li><strong>لایهی ۳ (ادمین):</strong> <code>POST /authorization/sync</code> در xIds + Endpoint <code>POST /authorization/cache/clear</code> در هر مصرفکننده (محافظتشده با <code>XPolicies.EnabledAdmin</code>) برای پاکسازی دستی.</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<!-- ===================== بخش ۱۲ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۱۲</div>
|
||
<div class="section-title">
|
||
<h3>گام ۱۲ — تست، ملاحظات امنیتی و چکلیست نهایی</h3>
|
||
<div class="subtitle">Step 12: Tests, Security & Final Checklist</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<h4>۱۲.۱ تست واحد</h4>
|
||
<p class="no-indent">در Workspace فعلی پروژهی تست .NET وجود ندارد (<code>xFrameworkTest</code> یک پروژهی Cordova است). پروژهی جدید <code>Tests/xAuthorizationService.Tests</code> (xUnit، <code>netcoreapp3.1</code>) با <code>XBaseInMemoryRepository</code> فریمورک پیشنهاد میشود:</p>
|
||
|
||
<div class="code-box"><span class="file">Tests/xAuthorizationService.Tests/XPolicyDefinitionExtensionsTests.cs</span><pre>using Xunit;
|
||
using System.Linq;
|
||
using IdentityModel;
|
||
using xIdentityHelper;
|
||
using xCommons.Authorization;
|
||
using xAuthorizationService.Constants;
|
||
using xAuthorizationService.Extensions;
|
||
using xAuthorizationService.Models.Entities;
|
||
using Microsoft.AspNetCore.Authorization.Infrastructure;
|
||
|
||
namespace xAuthorizationService.Tests
|
||
{
|
||
public class XPolicyDefinitionExtensionsTests
|
||
{
|
||
[Fact]
|
||
public void EnabledChiefClerk_Dynamic_Equals_Static()
|
||
{
|
||
//
|
||
// Static (today) ...
|
||
var expected = XAuthorizationHelper.GetXAuthorizationPolicies()[XPolicies.EnabledChiefClerk];
|
||
|
||
//
|
||
// Dynamic ...
|
||
var definition = new XPolicyDefinition
|
||
{
|
||
Name = XPolicies.EnabledChiefClerk,
|
||
Kind = XPolicyKind.RoleBased,
|
||
MinRoleWeight = (int)XUserRole.ChiefClerk,
|
||
RequireEnabledUser = true
|
||
};
|
||
var roles = new[] { XUserRoles.CHIEF_CLERK, XUserRoles.JOURNALIST, XUserRoles.RESPONSIBLE_MANAGER, XUserRoles.ADMIN };
|
||
var actual = definition.ToAuthorizationPolicy(roles);
|
||
|
||
//
|
||
// Same Role Requirement ...
|
||
var expectedRoles = expected.Requirements.OfType<RequiredRolesRequirement>().Single().Roles;
|
||
var actualRoles = actual.Requirements.OfType<RequiredRolesRequirement>().Single().Roles;
|
||
Assert.Equal(expectedRoles.OrderBy(r => r), actualRoles.OrderBy(r => r));
|
||
|
||
//
|
||
// Same Claim Requirements (IsBanned / IsEnabled) ...
|
||
var expectedClaims = expected.Requirements.OfType<ClaimsAuthorizationRequirement>().Select(c => c.ClaimType).OrderBy(c => c);
|
||
var actualClaims = actual.Requirements.OfType<ClaimsAuthorizationRequirement>().Select(c => c.ClaimType).OrderBy(c => c);
|
||
Assert.Equal(expectedClaims, actualClaims);
|
||
|
||
//
|
||
Assert.Contains(actual.Requirements, r => r is DenyAnonymousAuthorizationRequirement);
|
||
}
|
||
|
||
[Fact]
|
||
public void WriteAccess_ScopeBased_Has_Read_And_Write()
|
||
{
|
||
//
|
||
var definition = new XPolicyDefinition
|
||
{
|
||
Name = XPolicies.WriteAccess,
|
||
Kind = XPolicyKind.ScopeBased,
|
||
RequiredScopes = "XAPI.read,XAPI.write",
|
||
RequireAuthenticatedUser = false
|
||
};
|
||
|
||
//
|
||
var policy = definition.ToAuthorizationPolicy(null);
|
||
var scope = policy.Requirements.OfType<ClaimsAuthorizationRequirement>().Single();
|
||
|
||
//
|
||
Assert.Equal(JwtClaimTypes.Scope, scope.ClaimType);
|
||
Assert.Equal(new[] { "XAPI.read", "XAPI.write" }, scope.AllowedValues);
|
||
}
|
||
}
|
||
}</pre></div>
|
||
|
||
<div class="code-box"><span class="file">Tests/xAuthorizationService.Tests/XRoleHierarchyResolverTests.cs</span><pre>[Fact]
|
||
public async Task MinWeight_4_Returns_ActuaryAssistant_And_Above()
|
||
{
|
||
//
|
||
var repository = new XRoleDefinitionInMemoryRepository(new XDataServiceConfiguration());
|
||
foreach (XUserRole role in Enum.GetValues(typeof(XUserRole)))
|
||
{
|
||
await repository.AddAsync(new XRoleDefinition { Name = role.GetStringValue(), Weight = (int)role, IsEnabled = true });
|
||
}
|
||
|
||
//
|
||
var resolver = new XRoleHierarchyResolver(repository);
|
||
var result = (await resolver.GetRolesByMinWeightAsync(4)).ToList();
|
||
|
||
//
|
||
Assert.Equal(7, result.Count);
|
||
Assert.Contains(XUserRoles.ACTUARY_ASSISTANT, result);
|
||
Assert.DoesNotContain(XUserRoles.REPORTER, result);
|
||
Assert.Contains(XUserRoles.ADMIN, result);
|
||
}</pre></div>
|
||
|
||
<h4>۱۲.۲ ملاحظات امنیتی (باید در Provider اعمال شوند)</h4>
|
||
<table class="styled-table">
|
||
<thead><tr><th>ریسک</th><th>کنترل</th><th>محل</th></tr></thead>
|
||
<tbody>
|
||
<tr><td>حذف/غیرفعالکردن <code>adminPolicy</code> / <code>enabledAdminPolicy</code></td><td><code>IsSystem</code> → فقط <code>DisplayName</code> قابل ویرایش؛ <code>IsEnabled=false</code> روی این دو ممنوع</td><td><code>XAuthorizationProvider+Policy.UpdatePolicyAsync</code></td></tr>
|
||
<tr><td>حذف نقش <code>admin</code> یا کاهش Weight آن</td><td><code>admin</code> همیشه <code>IsSystem</code> و <code>Weight = 10</code> ثابت؛ هنگام Update اگر <code>Name == XUserRoles.ADMIN</code> → <code>XException.NotAllowed</code></td><td><code>+Role.UpdateRoleAsync</code></td></tr>
|
||
<tr><td>Privilege escalation با Policy ضعیف</td><td>اگر <code>MinRoleWeight</code> درخواستی < Weight نقش ایجادکننده و ایجادکننده <code>admin</code> نیست → <code>XException.NotAllowed</code></td><td><code>+Policy.AddPolicyAsync</code> با <code>userInfo.Roles</code></td></tr>
|
||
<tr><td>حذف نقش دارای عضو</td><td><code>IXRoleSyncService.CountUsersInRoleAsync > 0</code> → <code>XException.ActionFailed</code></td><td><code>+Role.RemoveRoleAsync</code></td></tr>
|
||
<tr><td>Scope بدون ApiResource</td><td><code>ApiResourceName</code> اجباری؛ <code>XIdentityServerScopeSyncService</code> وجود Resource را در <code>ConfigurationDbContext.ApiResources</code> بررسی میکند</td><td><code>+Scope.AddScopeAsync</code></td></tr>
|
||
<tr><td>توکنهای صادرشدهی قبلی</td><td>تغییر Role/Scope روی توکنهای فعال اثر ندارد (Claims داخل JWT است)؛ Lifetime توکن کوتاه + <code>XIdentityTokenRefresher</code></td><td>سیاست عملیاتی</td></tr>
|
||
<tr><td>Audit</td><td><code>XRequestLoggingMiddleware</code> فعلی همهی درخواستهای <code>/authorization/*</code> را ثبت میکند؛ Hub SignalR هر تغییر را Push میکند</td><td>موجود</td></tr>
|
||
</tbody>
|
||
</table>
|
||
|
||
<h4>۱۲.۳ چکلیست نهایی اجرا</h4>
|
||
<table class="styled-table">
|
||
<thead><tr><th>#</th><th>گام</th><th>معیار پذیرش</th></tr></thead>
|
||
<tbody>
|
||
<tr><td>۱–۲</td><td>پروژه و ساختار</td><td><code>dotnet build Modules/xAuthorizationService</code> موفق</td></tr>
|
||
<tr><td>۳</td><td>Entities / Dtos / Constants</td><td>۳ Entity با <code>Name</code> یکتا، <code>IsSystem</code>، Dtoها با لیست</td></tr>
|
||
<tr><td>۴</td><td>Blueprint Wiring (۵۴ فایل)</td><td>بدون منطق؛ Build سبز</td></tr>
|
||
<tr><td>۵</td><td>Helper + DI</td><td><code>AddXAuthorizationService<T></code> سه Descriptor ثبت میکند؛ Hubها در <code>/hubs/*</code> در دسترساند</td></tr>
|
||
<tr><td>۶</td><td>Resolver + Policy Builder</td><td>تست <code>EnabledChiefClerk_Dynamic_Equals_Static</code> سبز</td></tr>
|
||
<tr><td>۷</td><td>Cache + Dynamic Provider</td><td>Policy ناموجود در DB به Fallback میرسد (<code>LocalApi.PolicyName</code> همچنان کار میکند)</td></tr>
|
||
<tr><td>۸</td><td>Provider + Seeder</td><td>پس از اولین اجرا: ۴ Scope / ۱۱ Role / ۳۰ Policy با <code>IsSystem=true</code></td></tr>
|
||
<tr><td>۹</td><td>xIds Integration</td><td>Migration <code>InitAuthorization</code> اعمال؛ <code>XAuthorization.db</code> ساخته میشود؛ تمام اکشنهای فعلی xIds بدون تغییر رفتار</td></tr>
|
||
<tr><td>۱۰</td><td>AuthorizationController</td><td>Swagger ۱۶ Endpoint نمایش میدهد؛ <code>POST policies</code> + استفادهی فوری بدون restart</td></tr>
|
||
<tr><td>۱۱</td><td>Handlers + Consumers</td><td>کاربر دونقشه با نقش دوم مجاز میشود؛ xAiApi Policy پویا را از xIds میخواند</td></tr>
|
||
<tr><td>۱۲</td><td>Tests + Security</td><td>همهی تستها سبز؛ حذف <code>admin</code> / <code>enabledAdminPolicy</code> → 400 <code>NotAllowed</code></td></tr>
|
||
</tbody>
|
||
</table>
|
||
|
||
<div class="comparison-grid">
|
||
<div class="comparison-card">
|
||
<h4>قبل (ایستا)</h4>
|
||
<ul>
|
||
<li><span>افزودن نقش</span><span class="value" style="color:var(--danger)">۴ فایل + Deploy همه</span></li>
|
||
<li><span>افزودن Policy</span><span class="value" style="color:var(--danger)">~۵۰ خط + Deploy</span></li>
|
||
<li><span>سلسلهمراتب</span><span class="value">لیست دستی تکراری</span></li>
|
||
<li><span>کاربر چندنقشه</span><span class="value" style="color:var(--danger)">فقط نقش اول</span></li>
|
||
<li><span>Multi-instance</span><span class="value" style="color:var(--danger)">static Dictionary</span></li>
|
||
</ul>
|
||
</div>
|
||
<div class="comparison-card recommended">
|
||
<span class="card-badge">بعد از ۱۲ گام</span>
|
||
<h4>پویا</h4>
|
||
<ul>
|
||
<li><span>افزودن نقش</span><span class="value">POST /authorization/roles</span></li>
|
||
<li><span>افزودن Policy</span><span class="value">POST /authorization/policies</span></li>
|
||
<li><span>سلسلهمراتب</span><span class="value">Weight + ParentRoleName</span></li>
|
||
<li><span>کاربر چندنقشه</span><span class="value">همهی Claimها</span></li>
|
||
<li><span>Multi-instance</span><span class="value">Cache TTL + Event + Sync</span></li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="conclusion-box">
|
||
<h3>جمعبندی</h3>
|
||
<p>با ۱۲ گام این مستند، ماژول <code>xAuthorizationService</code> دقیقاً روی Blueprint موجود فریمورک (xDataService / xPushService / xIdentityService) سوار میشود. هیچیک از ثابتهای <code>XPolicies.*</code>، <code>XUserRoles.*</code> و <code>XApiScopes.*</code> حذف نمیشوند؛ آنها به رکوردهای <code>IsSystem</code> تبدیل شده و Fallback به <code>DefaultAuthorizationPolicyProvider</code> سازگاری عقبرو را تضمین میکند.</p>
|
||
<div class="highlight">
|
||
<strong>ترتیب اجرا:</strong><br>
|
||
گام ۱–۵ (اسکلت و Wiring) ← گام ۶–۷ (Builder/Provider + تست واحد) ← گام ۸ (Seeder) ← گام ۹–۱۰ (xIds) ← گام ۱۱ (Handlers/Consumers) ← گام ۱۲ (امنیت و تست یکپارچه)
|
||
</div>
|
||
</div>
|
||
|
||
<div class="info-box">
|
||
<strong>فرضها و محدودیتها:</strong>
|
||
(۱) ساختار <code>XEFRepositoryDescriptor</code> با ۱۵ پارامتر جنریک بر اساس <code>XTagServiceHelper</code> فعلی است؛ اگر نسخهی Seeder-dar (۱۷ پارامتر) لازم شد از همان الگو استفاده کنید.
|
||
(۲) <code>xEventService</code> فعلاً Consumer ندارد؛ لایهی ۲ invalidation پس از افزودن آن تکمیل میشود.
|
||
(۳) <code>XDataServiceConstants.XAuthorizationDbIdentifier</code> باید در <code>xIds/Constants/XDataServiceConstants.cs</code> با مقدار <code>"xAuthorizationDb"</code> افزوده شود.
|
||
(۴) امضای <code>XUserClaimsInfoDto(accessToken, refreshToken, expiresAt, claims)</code> بر اساس <code>XIBaseController.GetUserInfo</code> است.
|
||
(۵) نمونهکدها Compile-ready طراحی شدهاند اما در این مستند Build نشدهاند؛ پس از هر گام <code>dotnet build</code> بزنید.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="page-info">
|
||
این مستند برای استفادهی داخلی تیم توسعه xSaherelm تهیه شده و ادامهی مستند <code>1405-08-23_Overview_v.2</code> بر اساس وضعیت سورسکد در تاریخ ۱۴۰۵/۰۸/۲۳ است.
|
||
</div>
|
||
|
||
</div>
|
||
|
||
<footer class="document-footer">
|
||
<div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
|
||
<div class="footer-divider"></div>
|
||
<div>تاریخ تهیه: ۲۳ آبان ۱۴۰۵ | نسخه: ۳.۰ | طبقهبندی: داخلی / فنی</div>
|
||
</footer>
|
||
|
||
</div>
|
||
|
||
</body>
|
||
</html>
|