سياسات CORS وCSP والرؤوس الآمنة
تقييد الوصول عبر المصادر وإضافة رؤوس أمان محصّنة دون تعطيل العملاء المشروعة.
سياسات CORS وCSP والرؤوس الآمنة درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في FastAPI Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Headers Are Your Outer Perimeter
Before a request ever reaches your business logic, the browser and your server negotiate trust through HTTP headers. Two families dominate API hardening:
- CORS (Cross-Origin Resource Sharing) decides which browser origins may read your responses.
- Security response headers (CSP, HSTS, X-Frame-Options, etc.) tell the browser how to constrain the page it renders.
The goal of this lesson is to lock down cross-origin access and inject hardened headers without breaking legitimate clients. Misconfigure them and you either leak data to any website or block your own frontend.
The CORS Mental Model
CORS is enforced by the browser, not your server. Your API simply emits Access-Control-* headers; the browser decides whether to expose the response to JavaScript.
- A simple request (GET/POST with safe headers) is sent immediately; the browser checks
Access-Control-Allow-Originon the response. - A preflight
OPTIONSrequest is sent first for non-simple methods (PUT, DELETE) or custom headers likeAuthorization.
Critically: CORS does not protect server-to-server calls, curl, or mobile apps. It is purely a browser same-origin relaxation mechanism.
Configuring CORSMiddleware
FastAPI ships Starlette's CORSMiddleware. The cardinal rule: never combine allow_origins=["*"] with allow_credentials=True — the browser rejects that pairing, and it would be a data-leak anyway.
Pin an explicit allow-list of origins instead of a wildcard.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=[
"https://app.example.com",
"https://admin.example.com",
],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
max_age=600,
)Wildcards, Credentials and Regex
When you must accept many subdomains, do not fall back to "*". Use allow_origin_regex so the browser still gets back the exact origin it sent, which is required for credentialed requests.
allow_methods=["*"]andallow_headers=["*"]are tolerable, but only whenallow_credentials=False.- With credentials on, every value must be explicit or regex-matched.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origin_regex=r"https://([a-z0-9-]+)\.example\.com",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["Authorization", "Content-Type"],
expose_headers=["X-Request-ID"],
)Validating an Origin Allow-List in Pure Python
The logic CORS middleware runs is conceptually simple: reflect the request origin only if it passes validation. Here is a standalone validator you could unit-test, mirroring how a custom origin check behaves before any framework is involved.
import re
ALLOWED = {"https://app.example.com", "https://admin.example.com"}
SUBDOMAIN = re.compile(r"^https://[a-z0-9-]+\.example\.com$")
def resolve_allow_origin(origin: str) -> str | None:
if origin in ALLOWED or SUBDOMAIN.match(origin):
return origin # echo exact origin back
return None # do not emit Access-Control-Allow-Origin
for test in [
"https://app.example.com",
"https://team-7.example.com",
"https://evil.com",
"http://app.example.com",
]:
print(test, "->", resolve_allow_origin(test))Hardening Headers with a Custom Middleware
CORS handles cross-origin reads; a separate middleware injects defensive headers on every response. The essentials:
Strict-Transport-Security(HSTS) forces HTTPS.X-Content-Type-Options: nosniffstops MIME sniffing.X-Frame-Options: DENYblocks clickjacking.Referrer-Policylimits leaked URLs.
from starlette.middleware.base import BaseHTTPMiddleware
HEADERS = {
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "geolocation=(), microphone=(), camera=()",
}
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
for key, value in HEADERS.items():
response.headers.setdefault(key, value)
return response
app.add_middleware(SecurityHeadersMiddleware)Content-Security-Policy Fundamentals
CSP is the most powerful header for stopping XSS. It tells the browser which sources are allowed for scripts, styles, images, and connections. For an API serving JSON, a very tight default works because no inline content is rendered.
default-src 'none'denies everything unless overridden.frame-ancestors 'none'is the modern replacement for X-Frame-Options.- For HTML pages, prefer a nonce over
'unsafe-inline'.
API_CSP = "; ".join([
"default-src 'none'",
"frame-ancestors 'none'",
"base-uri 'none'",
"form-action 'none'",
])
# Attach on the security middleware:
# response.headers.setdefault("Content-Security-Policy", API_CSP)
print(API_CSP)Nonce-Based CSP for HTML Responses
When your FastAPI app renders HTML (docs, an admin page), inline scripts need a per-response nonce. Generate a fresh random nonce on each request, place it in both the CSP header and the <script nonce=...> tag.
Here is the standalone nonce-generation logic you would reuse inside a request handler.
import secrets
def new_nonce() -> str:
return secrets.token_urlsafe(16)
def csp_with_nonce(nonce: str) -> str:
return "; ".join([
"default-src 'self'",
f"script-src 'self' 'nonce-{nonce}'",
"style-src 'self'",
"object-src 'none'",
"frame-ancestors 'none'",
])
n = new_nonce()
print("nonce:", n)
print(csp_with_nonce(n))Report-Only Rollout Without Breaking Clients
Deploying a strict CSP blindly will break legitimate pages. The safe path is Content-Security-Policy-Report-Only: the browser does not enforce the policy but reports violations to an endpoint you control.
- Ship report-only first, collect violations for days.
- Tighten directives until reports go quiet, then switch to the enforcing header.
This is the single most important practice for not locking out real users.
from fastapi import FastAPI, Request, Response
app = FastAPI()
CSP = "default-src 'self'; report-uri /csp-report"
@app.middleware("http")
async def csp_report_only(request: Request, call_next):
response: Response = await call_next(request)
response.headers.setdefault("Content-Security-Policy-Report-Only", CSP)
return response
@app.post("/csp-report")
async def collect(request: Request):
payload = await request.json()
# log payload["csp-report"] to your SIEM
return Response(status_code=204)Preflight, Caching and Performance
Each non-simple cross-origin call triggers a preflight OPTIONS round-trip. Tune it so you stay secure but fast:
- Set
max_age(emitted asAccess-Control-Max-Age) so browsers cache the preflight result. Chromium caps it at 2 hours. - Keep
allow_headersminimal — every custom header forces a preflight. - Avoid adding
Authorizationto simple GETs if you can pass it another safe way; otherwise expect a preflight.
Order matters in Starlette: middleware added last runs first (outermost). Add CORS so it wraps your security-header middleware, letting preflights short-circuit cleanly.
Putting It All Together
A hardened FastAPI bootstrap layers the pieces in the right order: security headers innermost, CORS outermost, with explicit origins and a tight CSP. This is the template you would deploy to production.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
SEC = {
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
}
class SecHeaders(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
resp = await call_next(request)
for k, v in SEC.items():
resp.headers.setdefault(k, v)
return resp
app = FastAPI()
app.add_middleware(SecHeaders) # added first -> runs inner
app.add_middleware( # added last -> runs outer
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
max_age=600,
)Quick Check: Credentialed CORS
Your React frontend at https://app.example.com sends authenticated requests with cookies, so it needs allow_credentials=True. What is the correct origin configuration?
Recap and Takeaways
You hardened the request perimeter without locking out real clients:
- CORS is browser-enforced: use an explicit allow-list or
allow_origin_regex, and never pair"*"withallow_credentials=True. - Security headers (HSTS, nosniff, Referrer-Policy, Permissions-Policy) belong on every response via a small middleware.
- CSP is your strongest anti-XSS control:
default-src 'none'for JSON APIs, nonce-based policies for HTML. - Roll out CSP with Report-Only first, watch violations, then enforce.
- Tune
max_ageand minimalallow_headersto keep preflights cheap, and remember middleware order: added last runs outermost.
Secure defaults plus a measured rollout is how you ship hardening that production traffic survives.
تعلم FastAPI Backend Development Bootcamp مع معلم ذكاء اصطناعي — مجانًا
اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.
- الدورات
- 21
- الدروس
- 84
الأسئلة الشائعة
هل درس «سياسات CORS وCSP والرؤوس الآمنة» مجاني؟
نعم — نص درس «سياسات CORS وCSP والرؤوس الآمنة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
ماذا ستتعلم في «سياسات CORS وCSP والرؤوس الآمنة»؟
تقييد الوصول عبر المصادر وإضافة رؤوس أمان محصّنة دون تعطيل العملاء المشروعة. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ FastAPI Backend Development Bootcamp؟
لا تُشترط خبرة سابقة. FastAPI Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.
كم من الوقت يستغرق درس «سياسات CORS وCSP والرؤوس الآمنة»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس FastAPI Backend Development Bootcamp هذا؟
نعم. كل درس في FastAPI Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- الحد من مخاطر OWASP API Security Top 10
- تحديد معدل الطلبات والحماية من إساءة استخدام الروبوتات
- إدارة الأسرار وتدوير المفاتيح
- سياسات CORS وCSP والرؤوس الآمنة