Files
xSaherelmWorkspace/Documents/Docs/Developer/Authentication and Authorization in MCP Server Implementation Pure using c#.html
T
saherelm 0d6965215e - افزودن xAiMcpServer به .gitmodules به‌عنوان submodule جدید.
- افزودن پروژه و pointer مربوط به xAiMcpServer به xSaherelmWorkspace.sln و root.
- به‌روزرسانی .vscode/launch.json و .vscode/tasks.json برای ساختار جدید.
- به‌روزرسانی Documents/Resources/Commands/AiApi.txtx برای تولید context مربوط به
  xAiMcpServer در کنار xAiApi، xAiModels و xAiService.
- حذف contextهای قدیمی xDashboard-xAiApi/xAiModels/xAiService مربوط به 20261102 و
  ایجاد contextهای جدید 20261104 برای xAiApi، xAiMcpServer، xAiModels و xAiService.
2026-11-04 17:52:15 +03:30

1018 lines
44 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>احراز هویت و اعتبارسنجی در MCP Server | راهنمای گام‌به‌گام C#</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&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;
--code-bg: #1e293b;
--code-text: #e2e8f0;
--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: 1080px;
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: 27px;
font-weight: 800;
margin-bottom: 10px;
letter-spacing: -0.5px;
}
.document-title h2 { font-size: 15px; 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: 45px; 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); font-family: 'JetBrains Mono', monospace; direction: ltr; text-align: right; }
.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; }
.highlight-box, .info-box, .success-box, .warning-box, .danger-box {
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.highlight-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #f6e05e;
border-right: 4px solid var(--accent);
}
.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);
}
.success-box {
background: linear-gradient(to left, #f0fff4, #e6fffa);
border: 1px solid #9ae6b4;
border-right: 4px solid var(--success);
}
.warning-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #fbd38d;
border-right: 4px solid var(--warning);
}
.danger-box {
background: linear-gradient(to left, #fff5f5, #fed7d7);
border: 1px solid #fc8181;
border-right: 4px solid var(--danger);
}
pre {
background: var(--code-bg);
color: var(--code-text);
padding: 20px 22px;
border-radius: 8px;
overflow-x: auto;
margin: 15px 0;
font-family: 'JetBrains Mono', 'Courier New', monospace;
font-size: 12.5px;
line-height: 1.7;
direction: ltr;
text-align: left;
border: 1px solid #334155;
position: relative;
}
pre::before {
content: attr(data-lang);
position: absolute;
top: 8px;
right: 12px;
font-size: 10px;
color: #64748b;
text-transform: uppercase;
letter-spacing: 1px;
font-weight: 600;
}
code {
font-family: 'JetBrains Mono', 'Courier New', monospace;
background: #f1f5f9;
color: #1e293b;
padding: 2px 6px;
border-radius: 4px;
font-size: 12.5px;
direction: ltr;
display: inline-block;
}
pre code { background: none; color: inherit; padding: 0; display: inline; }
.file-path {
background: #2c5282;
color: #bee3f8;
padding: 8px 14px;
border-radius: 6px 6px 0 0;
font-family: 'JetBrains Mono', monospace;
font-size: 11.5px;
direction: ltr;
text-align: left;
margin-top: 15px;
margin-bottom: -15px;
border-bottom: 2px solid #1a365d;
}
.file-path::before { content: '📄 '; margin-left: 4px; }
.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; }
.checklist { list-style: none; padding: 0; margin: 15px 0; }
.checklist li {
padding: 10px 15px;
background: #f8fafc;
border-right: 3px solid var(--primary-light);
margin-bottom: 8px;
border-radius: 6px;
font-size: 13.5px;
}
.checklist li::before {
content: '✓';
color: var(--success);
font-weight: 700;
margin-left: 10px;
display: inline-block;
}
.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; } .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>شماره مستند: GUIDE-MCP-AUTH-1405-001</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: آبان ۱۴۰۵</div>
<div>طبقه‌بندی: آموزشی-فنی</div>
</div>
</div>
<div class="document-title">
<span class="label">SECURITY & VALIDATION GUIDE</span>
<h1>احراز هویت و اعتبارسنجی در MCP Server</h1>
<h2>پیاده‌سازی JWT، مجوزدهی سطح ابزار، و اعتبارسنجی ورودی در C# .NET</h2>
</div>
</header>
<div class="document-body">
<div class="intro-text">
<strong>هدف مستند:</strong><br>
این مستند، راهنمای گام‌به‌گام افزودن <strong>احراز هویت (Authentication)</strong>، <strong>مجوزدهی (Authorization)</strong>، و <strong>اعتبارسنجی ورودی (Validation)</strong> به یک MCP Server ساخته‌شده با <strong>ModelContextProtocol C# SDK</strong> است. برخلاف مستند قبلی که سرور پایه را می‌ساخت، تمرکز اینجا بر <strong>امنیت</strong> است: چگونه مطمئن شویم فقط کاربران مجاز به ابزارها دسترسی دارند، و چگونه ورودی‌های ارسالی مدل زبانی را قبل از اجرا اعتبارسنجی کنیم. در پایان، یک MCP Server امن و آماده برای محیط عملیاتی خواهید داشت.
</div>
<!-- ============================================================= -->
<!-- SECTION 0: Auth در MCP -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۰</div>
<div class="section-title">
<h3>احراز هویت در MCP چگونه کار می‌کند؟</h3>
<div class="subtitle">How MCP Authentication Works</div>
</div>
</div>
<div class="section-content">
<p>MCP یک پروتکل <strong>مستقل از Transport</strong> است و احراز هویت در آن بر اساس نوع Transport تعریف می‌شود. مشخصات رسمی MCP تأکید می‌کند که:</p>
<ul class="checklist">
<li>برای <strong>HTTP Transport</strong>: باید از <strong>OAuth 2.1</strong> و <strong>OAuth 2.0 Protected Resource Metadata (RFC 9728)</strong> پیروی شود</li>
<li>برای <strong>STDIO Transport</strong>: نباید از OAuth استفاده شود؛ اعتبارنامه‌ها باید از <strong>متغیرهای محیطی (Environment Variables)</strong> خوانده شوند</li>
<li>برای سایر Transportها: باید از بهترین روش‌های امنیتی همان پروتکل پیروی شود</li>
</ul>
<div class="info-box">
<strong>💡 نکته کلیدی:</strong> MCP Server در حالت HTTP نقش <strong>OAuth 2.1 Resource Server</strong> را بازی می‌کند و توکن‌های دسترسی (Access Tokens) را از کلاینت دریافت و اعتبارسنجی می‌کند. MCP Client نیز نقش <strong>OAuth 2.1 Client</strong> را دارد و توکن را از Authorization Server دریافت می‌کند.
</div>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">مقایسه دو رویکرد بر اساس Transport:</h4>
<table class="styled-table">
<thead>
<tr>
<th>ویژگی</th>
<th>HTTP Transport (JWT Bearer)</th>
<th>STDIO Transport (Environment Variables)</th>
</tr>
</thead>
<tbody>
<tr>
<td>مکانیزم احراز هویت</td>
<td>OAuth 2.1 / JWT Bearer Token</td>
<td>متغیرهای محیطی</td>
</tr>
<tr>
<td>اعتبارنامه</td>
<td><code>Authorization: Bearer &lt;token&gt;</code></td>
<td><code>API_KEY</code>، <code>DB_PASSWORD</code> و...</td>
</tr>
<tr>
<td>ذخیره امن</td>
<td>Authorization Server</td>
<td>فایل <code>.env</code> یا Secret Manager</td>
</tr>
<tr>
<td>مناسب برای</td>
<td>محیط Cloud، چند کاربر، راه دور</td>
<td>ابزارهای محلی، دسکتاپ</td>
</tr>
<tr class="highlight-row">
<td><strong>سطح امنیت</strong></td>
<td style="color: var(--success); font-weight: 600;">بالا (استاندارد OAuth)</td>
<td>متوسط (وابسته به محیط)</td>
</tr>
</tbody>
</table>
<div class="success-box">
<strong>✓ توصیه:</strong> اگر MCP Server شما قرار است از راه دور (Remote) در دسترس باشد، <strong>حتماً HTTP Transport با JWT Bearer</strong> را انتخاب کنید. اگر فقط یک ابزار محلی برای Claude Desktop هستید، STDIO با متغیرهای محیطی کافی است.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 1: HTTP + JWT -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>پیاده‌سازی احراز هویت HTTP با JWT Bearer</h3>
<div class="subtitle">JWT Bearer Authentication for HTTP Transport</div>
</div>
</div>
<div class="section-content">
<p>در این روش، MCP Server شما به یک <strong>Authorization Server</strong> (مانند Auth0، Keycloak، Duende IdentityServer، یا Azure AD) متصل می‌شود و توکن‌های JWT را اعتبارسنجی می‌کند. کلاینت MCP باید در هر درخواست، توکن معتبر را در هدر <code>Authorization</code> قرار دهد.</p>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">گام ۱: نصب پکیج‌های لازم</h4>
<pre data-lang="bash"><code>dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package ModelContextProtocol.AspNetCore</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">گام ۲: پیکربندی JWT در Program.cs</h4>
<div class="file-path">Program.cs</div>
<pre data-lang="csharp"><code>using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using ModelContextProtocol.Server;
var builder = WebApplication.CreateBuilder(args);
// ── ۱) ثبت سرویس احراز هویت JWT ──
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://your-auth-server.com"; // ← آدرس Authorization Server
options.Audience = "mcp-server"; // ← مخاطب مورد انتظار
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.FromMinutes(2)
};
});
builder.Services.AddAuthorization();
// ── ۲) ثبت MCP Server با HTTP Transport ──
builder.Services
.AddMcpServer()
.WithHttpTransport()
.AddAuthorizationFilters() // ← فیلترهای مجوزدهی سطح ابزار
.WithToolsFromAssembly();
var app = builder.Build();
app.UseAuthentication(); // ← فعال‌سازی Middleware احراز هویت
app.UseAuthorization(); // ← فعال‌سازی Middleware مجوزدهی
// ── ۳) محافظت از Endpoint MCP ──
app.MapMcp("/mcp").RequireAuthorization();
app.Run();</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">تشریح خط‌به‌خط:</h4>
<table class="styled-table">
<thead>
<tr>
<th>خط / بخش</th>
<th>نقش</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>AddAuthentication(JwtBearerDefaults.AuthenticationScheme)</code></td>
<td>ثبت مکانیزم احراز هویت پیش‌فرض به‌عنوان JWT Bearer</td>
</tr>
<tr>
<td><code>options.Authority</code></td>
<td>آدرس Authorization Server که توکن‌ها را صادر می‌کند (Discovery Endpoint)</td>
</tr>
<tr>
<td><code>options.Audience</code></td>
<td>شناسه MCP Server — توکن باید برای همین مخاطب صادر شده باشد</td>
</tr>
<tr>
<td><code>AddAuthorizationFilters()</code></td>
<td><strong>بحرانی:</strong> فیلترهای مجوزدهی سطح ابزار را فعال می‌کند تا <code>[Authorize]</code> روی متدهای Tool اجرا شود</td>
</tr>
<tr>
<td><code>app.MapMcp("/mcp").RequireAuthorization()</code></td>
<td>هر درخواست ناشناس (بدون توکن معتبر) با <strong>401 Unauthorized</strong> رد می‌شود</td>
</tr>
</tbody>
</table>
<div class="danger-box">
<strong>⚠️ هشدار امنیتی:</strong> اگر <code>RequireAuthorization()</code> را فراموش کنید، MCP Server شما <strong>کاملاً باز</strong> خواهد بود و هر کسی می‌تواند ابزارهای شما را فراخوانی کند. این خط را هرگز حذف نکنید.
</div>
<div class="info-box">
<strong>💡 نکته درباره OAuth 2.0 Protected Resource Metadata:</strong> بر اساس مشخصات MCP، سرورهای HTTP <strong>باید</strong> یک Endpoint در مسیر <code>/.well-known/oauth-protected-resource</code> ارائه دهند تا کلاینت بتواند Authorization Server را کشف کند. SDK این کار را تا حدی خودکار انجام می‌دهد، اما برای کنترل کامل می‌توانید یک Endpoint سفارشی اضافه کنید:
<br><br>
<code>app.MapGet("/.well-known/oauth-protected-resource", () =&gt; Results.Json(new { authorization_servers = new[] { "https://your-auth-server.com" } }));</code>
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 2: STDIO Auth -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>احراز هویت در STDIO با متغیرهای محیطی</h3>
<div class="subtitle">STDIO Authentication via Environment Variables</div>
</div>
</div>
<div class="section-content">
<p>در Transport از نوع STDIO، پروتکل MCP از OAuth استفاده نمی‌کند. اعتبارنامه‌ها باید از طریق <strong>متغیرهای محیطی</strong> به پروسه سرور منتقل شوند. این روش برای ابزارهای محلی مانند Claude Desktop ایده‌آل است.</p>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">گام ۱: خواندن اعتبارنامه در سرور</h4>
<div class="file-path">Program.cs (نسخه STDIO)</div>
<pre data-lang="csharp"><code>var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(options =>
options.LogToStandardErrorThreshold = LogLevel.Trace);
// ── خواندن اعتبارنامه از متغیر محیطی ──
var apiKey = Environment.GetEnvironmentVariable("MY_MCP_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
Console.Error.WriteLine("FATAL: MY_MCP_API_KEY is not set.");
Environment.Exit(1);
}
// ثبت به‌عنوان Singleton برای استفاده در Tools
builder.Services.AddSingleton(new McpCredentials(apiKey));
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">گام ۲: پیکربندی کلاینت (Claude Desktop) برای ارسال متغیر محیطی</h4>
<pre data-lang="json"><code>{
"mcpServers": {
"secure-tool": {
"command": "dotnet",
"args": [ "run", "--project", "C:\\Path\\To\\SecureMcpServer.csproj" ],
"env": {
"MY_MCP_API_KEY": "your-secret-key-here"
}
}
}
}</code></pre>
<div class="warning-box">
<strong>⚠️ نکته امنیتی:</strong> هرگز کلیدهای حساس را مستقیماً در کد یا فایل <code>appsettings.json</code> قرار ندهید. از <strong>Secret Manager</strong> (مانند <code>dotnet user-secrets</code> در توسعه یا Azure Key Vault در عملیات) استفاده کنید. همچنین در سمت کلاینت، <code>InheritEnvironmentVariables = false</code> را تنظیم کنید تا فقط متغیرهای مشخص‌شده به سرور منتقل شوند و سایر اعتبارنامه‌های سیستم (مانند <code>AWS_SECRET_ACCESS_KEY</code>) لو نروند.
</div>
<div class="success-box">
<strong>✓ بهترین روش:</strong> در محیط توسعه از <code>dotnet user-secrets</code> و در محیط عملیاتی از Secret Manager ابری استفاده کنید. کلید را هرگز در مخزن Git قرار ندهید.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 3: Tool-Level Authorization -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>مجوزدهی در سطح ابزار (Tool-Level Authorization)</h3>
<div class="subtitle">Per-Tool Authorization with [Authorize]</div>
</div>
</div>
<div class="section-content">
<p>احراز هویت فقط می‌گوید «چه کسی وارد شده است». <strong>مجوزدهی</strong> می‌گوید «این کاربر چه کاری مجاز است انجام دهد». در MCP C# SDK، با فعال‌سازی <code>AddAuthorizationFilters()</code> می‌توانید از Attribute <code>[Authorize]</code> روی متدهای Tool استفاده کنید — دقیقاً مانند کنترلرهای ASP.NET Core.</p>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">الف) محدود کردن ابزار به کاربران دارای نقش خاص</h4>
<pre data-lang="csharp"><code>using Microsoft.AspNetCore.Authorization;
using ModelContextProtocol.Server;
using System.ComponentModel;
[McpServerToolType]
public class AdminTools
{
[McpServerTool, Description("Deletes a record permanently.")]
[Authorize(Roles = "Admin")] // ← فقط نقش Admin
public static string DeleteRecord(Guid id)
=> $"Record {id} deleted.";
[McpServerTool, Description("Reads public data.")]
[Authorize] // ← هر کاربر احراز هویت‌شده
public static string GetPublicData()
=> "Public data.";
}</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ب) استفاده از Policy سفارشی</h4>
<pre data-lang="csharp"><code>// ── در Program.cs، قبل از Build ──
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("CanManageOrders", policy =>
policy.RequireClaim("permission", "orders:write"));
});
// ── در Tool ──
[McpServerTool, Description("Updates an order.")]
[Authorize(Policy = "CanManageOrders")]
public static string UpdateOrder(string orderId)
=> $"Order {orderId} updated.";</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ج) دسترسی به هویت کاربر درون Tool</h4>
<p class="no-indent">با تزریق <code>IHttpContextAccessor</code> می‌توانید به Claims کاربر جاری دسترسی داشته باشید:</p>
<pre data-lang="csharp"><code>builder.Services.AddHttpContextAccessor();
[McpServerToolType]
public class UserAwareTools(IHttpContextAccessor httpContextAccessor)
{
[McpServerTool, Description("Returns the current user's ID.")]
public string GetCurrentUserId()
{
var user = httpContextAccessor.HttpContext?.User;
return user?.Identity?.Name ?? "anonymous";
}
}</code></pre>
<div class="danger-box">
<strong>⚠️ تفاوت احراز هویت و مجوزدهی:</strong> <code>RequireAuthorization()</code> روی <code>MapMcp</code> فقط تضمین می‌کند که <strong>یک کاربر معتبر</strong> وارد شده است. اما اگر <code>[Authorize]</code> روی ابزارها نداشته باشید، <strong>هر کاربر معتبری</strong> می‌تواند <strong>تمام ابزارها</strong> را فراخوانی کند. حتماً برای ابزارهای حساس، مجوزدهی سطح ابزار اضافه کنید.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 4: Input Validation -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>اعتبارسنجی ورودی ابزارها (Input Validation)</h3>
<div class="subtitle">Validating Tool Parameters</div>
</div>
</div>
<div class="section-content">
<p>مدل‌های زبانی ممکن است ورودی‌های نامعتبر یا مخرب ارسال کنند. اعتبارسنجی ورودی، خط دفاعی نهایی قبل از اجرای منطق تجاری است. دو رویکرد اصلی وجود دارد:</p>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">الف) Data Annotations (ساده و اعلانی)</h4>
<p class="no-indent">مناسب برای قوانین ساده مانند اجباری بودن، طول رشته، و محدوده عددی. این Attributeها هم در <strong>JSON Schema</strong> تولیدی اثر می‌گذارند و هم قابل اجرا هستند:</p>
<pre data-lang="csharp"><code>using System.ComponentModel.DataAnnotations;
public class CreateUserRequest
{
[Required(ErrorMessage = "Name is required.")]
[StringLength(100, MinimumLength = 2)]
public string Name { get; set; }
[Range(18, 120, ErrorMessage = "Age must be between 18 and 120.")]
public int Age { get; set; }
[EmailAddress]
public string Email { get; set; }
}
[McpServerTool, Description("Creates a new user.")]
public static string CreateUser(CreateUserRequest request)
{
// اعتبارسنجی دستی
var context = new ValidationContext(request);
var results = new List&lt;ValidationResult&gt;();
if (!Validator.TryValidateObject(request, context, results, validateAllProperties: true))
{
var errors = string.Join("; ", results.Select(r => r.ErrorMessage));
throw new ArgumentException($"Validation failed: {errors}");
}
return $"User {request.Name} created.";
}</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ب) FluentValidation (برای قوانین پیچیده)</h4>
<p class="no-indent">برای قوانین شرطی، وابسته به چند فیلد، یا اعتبارسنجی‌های پیچیده‌تر:</p>
<pre data-lang="csharp"><code>using FluentValidation;
public class UpdateOrderValidator : AbstractValidator&lt;UpdateOrderRequest&gt;
{
public UpdateOrderValidator()
{
RuleFor(x => x.OrderId).NotEmpty().WithMessage("Order ID is required.");
RuleFor(x => x.Quantity).GreaterThan(0).WithMessage("Quantity must be positive.");
RuleFor(x => x.DiscountCode)
.MaximumLength(20)
.When(x => !string.IsNullOrEmpty(x.DiscountCode));
}
}
[McpServerTool, Description("Updates an order.")]
public static async Task&lt;string&gt; UpdateOrder(UpdateOrderRequest request)
{
var validator = new UpdateOrderValidator();
var result = await validator.ValidateAsync(request);
if (!result.IsValid)
throw new ArgumentException(result.ToString());
return $"Order {request.OrderId} updated.";
}</code></pre>
<div class="info-box">
<strong>💡 نکته:</strong> SDK به‌طور خودکار <strong>JSON Schema</strong> را از امضای متد تولید می‌کند. اگر از Data Annotations استفاده کنید، محدودیت‌ها (مانند <code>maxLength</code>، <code>minimum</code>، <code>required</code>) در Schema ظاهر می‌شوند و مدل زبانی از قبل می‌داند چه ورودی معتبر است. این کار نرخ خطا را به‌طور قابل‌توجهی کاهش می‌دهد.
</div>
<div class="warning-box">
<strong>⚠️ هشدار:</strong> اعتبارسنجی سمت سرور را <strong>هرگز</strong> حذف نکنید، حتی اگر Schema محدودیت‌ها را نشان دهد. مدل زبانی همیشه از Schema پیروی نمی‌کند و ممکن است مقادیر خارج از محدوده ارسال کند.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 5: Filters -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>فیلترها: خط دفاعی سراسری</h3>
<div class="subtitle">Message & Request Filters for Cross-Cutting Security</div>
</div>
</div>
<div class="section-content">
<p>SDK MCP C# دو نوع فیلتر ارائه می‌دهد که برای امنیت سراسری بسیار مفید هستند:</p>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 15px;">الف) Message Filters (سطح JSON-RPC)</h4>
<p class="no-indent">همه پیام‌های ورودی و خروجی را رهگیری می‌کنند — مناسب برای لاگ امنیتی، Rate Limiting، و بازرسی محتوا:</p>
<pre data-lang="csharp"><code>builder.Services
.AddMcpServer()
.WithHttpTransport()
.WithMessageFilters(filters =>
{
filters.AddIncomingFilter(async (context, next) =>
{
var logger = context.Services.GetRequiredService&lt;ILogger&lt;Program&gt;&gt;();
logger.LogInformation("MCP incoming: {Method}", context.Message?.Method);
await next(context);
});
});</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">ب) Request Filters (سطح ابزار)</h4>
<p class="no-indent">مخصوص <code>tools/call</code> — مناسب برای بررسی مجوز سطح ابزار و لاگ دقیق:</p>
<pre data-lang="csharp"><code>.WithRequestFilters(filters =>
{
filters.AddCallToolFilter(async (context, next) =>
{
var logger = context.Services.GetRequiredService&lt;ILogger&lt;Program&gt;&gt;();
logger.LogInformation("Tool called: {ToolName}", context.Params?.Name);
// می‌توانید قبل از اجرا، دسترسی را بررسی کنید
var result = await next(context);
return result;
});
});</code></pre>
<div class="danger-box">
<strong>⚠️ هشدار مهم:</strong> فیلترها را به‌عنوان <strong>تنها</strong> لایه امنیتی در نظر نگیرید. اگر یک ابزار از لیست پنهان شده باشد اما همچنان قابل فراخوانی مستقیم باشد، فیلترها باید آن را رد کنند. همیشه از ترکیب <code>RequireAuthorization()</code> + <code>[Authorize]</code> + فیلترها استفاده کنید.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 6: Complete Example -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۶</div>
<div class="section-title">
<h3>نمونه کامل: MCP Server امن با JWT و Validation</h3>
<div class="subtitle">Complete Secure MCP Server Example</div>
</div>
</div>
<div class="section-content">
<div class="file-path">Program.cs</div>
<pre data-lang="csharp"><code>using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using ModelContextProtocol.Server;
var builder = WebApplication.CreateBuilder(args);
// ── احراز هویت JWT ──
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = builder.Configuration["Jwt:Authority"];
options.Audience = builder.Configuration["Jwt:Audience"];
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", p => p.RequireRole("Admin"));
});
builder.Services.AddHttpContextAccessor();
// ── MCP Server ──
builder.Services
.AddMcpServer()
.WithHttpTransport()
.AddAuthorizationFilters()
.WithToolsFromAssembly();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapMcp("/mcp").RequireAuthorization();
app.Run();</code></pre>
<div class="file-path">Tools/SecureTools.cs</div>
<pre data-lang="csharp"><code>using Microsoft.AspNetCore.Authorization;
using ModelContextProtocol.Server;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
[McpServerToolType]
public class SecureTools(IHttpContextAccessor httpContextAccessor)
{
// ابزار عمومی — فقط نیاز به احراز هویت
[McpServerTool, Description("Returns the current server time.")]
[Authorize]
public string GetTime() => DateTime.UtcNow.ToString("O");
// ابزار حساس — فقط Admin
[McpServerTool, Description("Deletes a record.")]
[Authorize(Policy = "AdminOnly")]
public string DeleteRecord(Guid id) => $"Deleted {id}";
// ابزار با اعتبارسنجی ورودی
[McpServerTool, Description("Creates a new item.")]
[Authorize]
public string CreateItem(CreateItemRequest request)
{
var ctx = new ValidationContext(request);
var results = new List&lt;ValidationResult&gt;();
if (!Validator.TryValidateObject(request, ctx, results, true))
throw new ArgumentException(string.Join("; ", results.Select(r => r.ErrorMessage)));
var userId = httpContextAccessor.HttpContext?.User?.Identity?.Name;
return $"Item '{request.Name}' created by {userId}.";
}
}
public class CreateItemRequest
{
[Required, StringLength(50, MinimumLength = 2)]
public string Name { get; set; }
[Range(1, 1000)]
public int Quantity { get; set; }
}</code></pre>
<div class="success-box">
<strong>✓ نتیجه:</strong> این سرور دارای سه لایه امنیتی است: (۱) احراز هویت JWT در سطح Endpoint، (۲) مجوزدهی سطح ابزار با <code>[Authorize]</code> و Policy، و (۳) اعتبارسنجی ورودی با Data Annotations. ابزار حساس «حذف» فقط برای Admin قابل دسترسی است و ابزار «ایجاد» ورودی‌های نامعتبر را رد می‌کند.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 7: Best Practices -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۷</div>
<div class="section-title">
<h3>بهترین روش‌ها و چک‌لیست امنیتی</h3>
<div class="subtitle">Security Best Practices & Checklist</div>
</div>
</div>
<div class="section-content">
<ul class="checklist">
<li><code>app.MapMcp(...).RequireAuthorization()</code> را هرگز حذف نکنید — این خط پایه امنیت است</li>
<li>روی <strong>هر ابزار حساس</strong> از <code>[Authorize]</code> با Role یا Policy مناسب استفاده کنید</li>
<li><code>AddAuthorizationFilters()</code> را فراموش نکنید؛ در غیر این صورت <code>[Authorize]</code> روی Toolها اجرا نمی‌شود</li>
<li>ورودی‌های Tool را با Data Annotations یا FluentValidation اعتبارسنجی کنید</li>
<li>در STDIO، اعتبارنامه‌ها را از متغیرهای محیطی بخوانید و هرگز در کد Hard-code نکنید</li>
<li>در HTTP، از OAuth 2.1 با <code>Audience</code> و <code>Issuer</code> معتبر استفاده کنید</li>
<li>فیلترهای ورودی/خروجی را برای لاگ امنیتی و شناسایی الگوهای مشکوک فعال کنید</li>
<li>دسترسی ابزارها را به اصل حداقل امتیاز (Least Privilege) محدود کنید</li>
<li>در محیط عملیاتی، HTTPS را الزامی کنید و توکن‌ها را با <code>ClockSkew</code> کوتاه اعتبارسنجی کنید</li>
<li>Endpoint <code>/.well-known/oauth-protected-resource</code> را برای کشف Authorization Server ارائه دهید</li>
</ul>
<div class="highlight-box">
<strong>🔑 فرمول امنیتی نهایی:</strong><br>
<code>RequireAuthorization()</code> + <code>AddAuthorizationFilters()</code> + <code>[Authorize]</code> روی ابزارها + <strong>اعتبارسنجی ورودی</strong> = MCP Server امن و آماده عملیات
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 8: Summary -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۸</div>
<div class="section-title">
<h3>جمع‌بندی</h3>
<div class="subtitle">Summary</div>
</div>
</div>
<div class="section-content">
<p>در این مستند، سه لایه اصلی امنیت را به MCP Server خود اضافه کردیم:</p>
<table class="styled-table">
<thead>
<tr>
<th>لایه</th>
<th>ابزار</th>
<th>نقش</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>احراز هویت</strong></td>
<td>JWT Bearer / Environment Variables</td>
<td>تشخیص هویت کاربر (چه کسی وارد شده)</td>
</tr>
<tr>
<td><strong>مجوزدهی</strong></td>
<td><code>[Authorize]</code> + Policy</td>
<td>تعیین سطح دسترسی (چه کاری مجاز است)</td>
</tr>
<tr>
<td><strong>اعتبارسنجی</strong></td>
<td>Data Annotations / FluentValidation</td>
<td>بررسی صحت ورودی (آیا داده معتبر است)</td>
</tr>
</tbody>
</table>
<div class="conclusion-box">
<h3>🎯 نتیجه نهایی</h3>
<p>MCP Server شما اکنون:</p>
<p style="font-size: 13px; line-height: 2;">
<strong>در برابر دسترسی غیرمجاز محافظت می‌شود، ابزارهای حساس را فقط به کاربران مجاز نشان می‌دهد، ورودی‌های نامعتبر را قبل از اجرا رد می‌کند، و با استانداردهای OAuth 2.1 و MCP سازگار است.</strong>
</p>
<div class="highlight">
<strong>💎 ارزش پیشنهادی:</strong><br>
امنیت چندلایه + سازگاری با استانداردهای باز + پیاده‌سازی ساده با Attributeها + آماده برای محیط عملیاتی
</div>
</div>
<div class="info-box">
<strong>📞 گام بعدی پیشنهادی:</strong> اکنون که سرور امن دارید، می‌توانید: (۱) آن را در Docker کانتینری کنید، (۲) در CI/CD قرار دهید، (۳) با یک MCP Client واقعی تست End-to-End انجام دهید، و (۴) ابزارهای بیشتری را با رعایت اصل حداقل دسترسی اضافه کنید.
</div>
</div>
</div>
<div class="page-info">
این مستند آموزشی بوده و برای تیم‌های فنی و توسعه‌دهندگان تهیه شده است. استفاده از آن در پروژه‌های داخلی و تجاری مجاز است.
</div>
</div>
<footer class="document-footer">
<div class="footer-brand">تهیه و تنظیم: تیم معماری xSaherelmWorkspace</div>
<div class="footer-divider"></div>
<div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: آموزشی-فنی</div>
</footer>
</div>
</body>
</html>