Content Security Policy & CORS
CSP (Content Security Policy) controls which resources browsers can load — preventing XSS by blocking inline scripts and unauthorized sources. CORS (Cross-Origin Resource Sharing) controls which domains can make API requests to your server.
15 min•By Priygop Team•Updated 2026
CSP & CORS
- CSP — HTTP header telling browsers what to load/execute
- CSP prevents inline scripts, unauthorized external resources
- CORS — Controls cross-origin API access
- django-csp — CSP middleware for Django
- django-cors-headers — CORS middleware for Django
- CORS is essential when API and frontend are on different domains
- Misconfigured CORS can block legitimate frontend requests
CSP & CORS Setup
CSP & CORS Setup
# CORS Setup
# pip install django-cors-headers
# settings.py
# INSTALLED_APPS = [..., 'corsheaders']
# MIDDLEWARE = [
# 'corsheaders.middleware.CorsMiddleware', # Before CommonMiddleware
# 'django.middleware.common.CommonMiddleware',
# ...
# ]
# Allow specific origins
# CORS_ALLOWED_ORIGINS = [
# 'https://yourdomain.com',
# 'https://app.yourdomain.com',
# 'http://localhost:3000', # React dev server
# ]
# Or allow all (development only!)
# CORS_ALLOW_ALL_ORIGINS = True
# CORS_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']
# CORS_ALLOW_HEADERS = ['authorization', 'content-type', 'x-csrftoken']
# CSP Setup (using django-csp or custom middleware)
# CSP_DEFAULT_SRC = ("'self'",)
# CSP_SCRIPT_SRC = ("'self'", 'https://cdn.example.com')
# CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", 'https://fonts.googleapis.com')
# CSP_IMG_SRC = ("'self'", 'data:', 'https:')
# CSP_FONT_SRC = ("'self'", 'https://fonts.gstatic.com')Tip
Tip
Use django-cors-headers for API backends. Set CORS_ALLOWED_ORIGINS explicitly — never use CORS_ALLOW_ALL_ORIGINS in production.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Setting CORS_ALLOW_ALL_ORIGINS=True in production. This allows any website to make requests to your API.
Practice Task
Note
(1) Install django-cors-headers. (2) Configure allowed origins. (3) Test cross-origin requests from a frontend.
Quick Quiz
Key Takeaways
- CSP (Content Security Policy) controls which resources browsers can load — preventing XSS by blocking inline scripts and unauthorized sources.
- CSP — HTTP header telling browsers what to load/execute
- CSP prevents inline scripts, unauthorized external resources
- CORS — Controls cross-origin API access