📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Cybersecurity and AI Security Security Headers

Security Headers

5 min read Quiz at the end
CSP, HSTS, X-Frame-Options, X-Content-Type-Options — set all security headers before launching.

HTTP Security Headers

# Essential security headers

# 1. Content-Security-Policy (prevent XSS)
Content-Security-Policy: default-src 'self';
    script-src 'self' https://cdn.example.com;
    style-src  'self' 'unsafe-inline';
    img-src    'self' data: https:;
    object-src 'none';
    frame-ancestors 'none';

# 2. HSTS (force HTTPS)
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

# 3. Prevent clickjacking
X-Frame-Options: DENY

# 4. Prevent MIME sniffing
X-Content-Type-Options: nosniff

# 5. Referrer policy
Referrer-Policy: strict-origin-when-cross-origin

# 6. Permissions policy
Permissions-Policy: camera=(), microphone=(), geolocation=()

# Test headers
# securityheaders.com
# observatory.mozilla.org

# FastAPI middleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['myapp.com','*.myapp.com'])

# CORS with security
app.add_middleware(CORSMiddleware,
    allow_origins=['https://myapp.com'],  # never wildcard in production
    allow_credentials=True)