The 403 is gone, the hole remains: CSRF vs CORS and why you need both
CORS doesn't stop a request, it only hides the response from the script. How SameSite, CSRF tokens, the Origin check and preflight work, and how to set up CSRF_TRUSTED_ORIGINS and django-cors-headers in Django without opening a hole.
One form, five million sum
Picture this: a user is logged into their online bank, and the browser holds a sessionid cookie. Then they open a "you won a prize" link from Telegram. The page looks blank, but it contains this form:
<!-- https://evil.example/yutuq.html -->
<form id="f" action="https://bank.example.uz/transfer/" method="POST">
<input type="hidden" name="to" value="8600123412341234">
<input type="hidden" name="amount" value="5000000">
</form>
<script>document.getElementById("f").submit();</script>
The browser submits the form to bank.example.uz and attaches the cookie on its own. From the server's point of view this is an ordinary authenticated POST: right session, right user. That is CSRF (Cross-Site Request Forgery). The attacker never even sees the response, and doesn't need to: the money is already gone.
Now a second scenario. The frontend lives on app.example.uz, the API on api.example.uz. A developer writes a fetch and the console turns red: "blocked by CORS policy". Once that's sorted, the POST starts returning 403: "CSRF verification failed". The fastest "fix" is always the same: CORS_ALLOW_ALL_ORIGINS = True and @csrf_exempt on the view. The frontend works. And the attack above is now wide open.
These two topics get mixed up constantly: both have "cross-origin" in them, and both show up as an error in the browser. In reality they solve problems that point in opposite directions. Let's pull them apart and see how to configure both correctly in Django.
Why the naive approach breaks
The usual misconceptions:
- "We have CORS configured, so a foreign site can't send requests." It can. CORS restricts reading the response, not sending the request. The HTML form above isn't subject to CORS at all: forms were posting to other sites long before CORS existed.
- "The API only accepts JSON, so it's safe." Only if the server actually requires
Content-Type: application/jsonand rejects everything else. If the view also readsrequest.POST, or parses the body regardless of content type, a plain form is enough. - "We use POST, not GET." Good, but plenty of projects also accept
request.GET"for convenience". - "The endpoint requires login." That is exactly why CSRF works: the attack rides on the user's logged-in session.
All of these mistakes in a single view:
# views.py: DON'T do this
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .services import transfer_money
@csrf_exempt # "the frontend kept getting 403, so..."
@login_required
def transfer(request):
# Also bad: GET is accepted too, so SameSite=Lax will not save us
data = request.POST or request.GET
transfer_money(request.user, data["to"], int(data["amount"]))
return JsonResponse({"ok": True})
CSRF: what the browser sends on its own
CSRF has one root cause: the browser attaches cookies based on the domain the request is going to, not the page it started from (at least historically; SameSite has partly changed that). If the server concludes "the user clicked this" from the cookie alone, it gets fooled. Every defense answers one question: did our own page really send this request?
SameSite cookies
The SameSite attribute tells the browser whether to send a cookie on cross-site requests:
| Value | Cookie on a cross-site request | Notes |
|---|---|---|
Strict |
Never sent | Even following a link from another site, the user looks "logged out" |
Lax |
Only on top-level GET navigation (clicking a link) | Django's default; not sent for POST forms, fetch, <img> |
None |
Always sent | Requires Secure, otherwise the browser rejects the cookie |
If the attribute is missing, Chromium-based browsers treat the cookie as Lax, but you can't rely on that across all browsers. Django sets SESSION_COOKIE_SAMESITE and CSRF_COOKIE_SAMESITE to "Lax" by default.
Two subtleties matter here. First, Lax lets GET navigations through, so a GET endpoint that changes state stays unprotected. Second, "site" is not "origin". A site is the scheme plus the registrable domain (example.uz), so blog.example.uz and api.example.uz are the same site. If some subdomain has an XSS hole or hosts content someone else controls, SameSite won't stop requests coming from there.
SameSite is a good extra layer, not the only defense. Django's CSRF check should run on top of it.
The CSRF token
The classic defense: the server puts an unpredictable token in the page and requires it on every POST. A foreign site can make the browser send the cookie, but it can't read it (same-origin policy), so it can't put the token in its own form.
In Django this is a "double submit" scheme. The csrftoken cookie holds a secret, and the page (via {% csrf_token %} or get_token()) gets a freshly masked version of that secret every time. Masking defends against BREACH-style attacks: the token looks different in every response. When a request arrives, the middleware takes the csrfmiddlewaretoken form field or the X-CSRFToken header, unmasks it and compares it with the secret from the cookie.
The Origin check
Since Django 4.0, CsrfViewMiddleware checks the Origin header first. The browser doesn't let page JavaScript forge it, so it's a reliable answer to "where did this request come from". The simplified logic:
# Simplified logic of CsrfViewMiddleware.process_view (not the real source)
SAFE_METHODS = ("GET", "HEAD", "OPTIONS", "TRACE")
def csrf_check(request):
if request.method in SAFE_METHODS:
return True
origin = request.META.get("HTTP_ORIGIN")
if origin is not None:
# must equal scheme://request.get_host() or match CSRF_TRUSTED_ORIGINS
if not origin_is_trusted(origin, request):
return False # 403: "Origin checking failed"
elif request.is_secure():
# HTTPS without Origin: Referer becomes mandatory and is checked strictly
if not referer_is_trusted(request):
return False
secret = read_csrf_cookie(request) # the csrftoken cookie
token = (
request.POST.get("csrfmiddlewaretoken")
or request.META.get("HTTP_X_CSRFTOKEN")
)
return tokens_match(secret, token) # unmask + constant-time compare
Note that Origin is compared as scheme://host. If the page is on https://app.example.uz and the API on https://api.example.uz, the origin won't match the host, and you'll need CSRF_TRUSTED_ORIGINS.
The fixed view needs no special code: the middleware is on by default, we just don't turn it off, and we close the GET door:
# views.py
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .forms import TransferForm
from .services import transfer_money
@login_required
@require_POST # state changes only via POST; GET gets 405
def transfer(request):
form = TransferForm(request.POST)
if not form.is_valid():
return JsonResponse({"errors": form.errors}, status=400)
transfer_money(
request.user,
form.cleaned_data["to"],
form.cleaned_data["amount"],
)
return JsonResponse({"ok": True})
What CORS actually is
Now the opposite direction. The browser enforces the same-origin policy: a script on evil.example can send a request to api.example.uz, but can't read the response. CORS (Cross-Origin Resource Sharing) is how the server tells the browser "this origin may read my responses". In other words, CORS is not a restriction; it's a way to relax an existing one.
Which leads to the main point: CORS is a browser policy, not server protection. It protects the user from foreign sites; it protects your server from nobody. For curl, Postman or another backend, CORS simply doesn't exist:
# No browser here, so no CORS. The request reaches Django as usual.
curl -sS -i -X POST https://api.example.uz/api/transfer/ \
-H 'Origin: https://evil.example' \
-H 'Content-Type: application/json' \
-d '{"to": "8600123412341234", "amount": 5000000}'
# Whatever stops it (403/401) comes from CSRF or auth, not from CORS.
Simple requests and preflight
The browser splits cross-origin requests into two kinds. A "simple" request is a GET, HEAD or POST with only basic headers and a Content-Type of application/x-www-form-urlencoded, multipart/form-data or text/plain. It is sent immediately, the server executes it, and only then, if the response lacks Access-Control-Allow-Origin, does the browser hide the response from the script. By that point the transfer has already happened.
For everything else (PUT, DELETE, application/json, custom headers like X-CSRFToken) the browser first sends an OPTIONS preflight, and sends the real request only if the server allows it:
// 1) "Simple" request: no preflight, the server EXECUTES it,
// the browser only hides the response from this script.
fetch("https://api.example.uz/api/transfer/", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: "to=8600123412341234&amount=5000000",
});
// 2) JSON + custom header: the browser sends OPTIONS first,
// and the real POST only goes out if the server allows it.
fetch("https://api.example.uz/api/transfer/", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json", "X-CSRFToken": "..." },
body: JSON.stringify({ to: "8600123412341234", amount: 5000000 }),
});
A preflight exchange looks roughly like this (a django-cors-headers response):
OPTIONS /api/transfer/ HTTP/1.1
Host: api.example.uz
Origin: https://app.example.uz
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, x-csrftoken
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.uz
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT
Access-Control-Allow-Headers: accept, authorization, content-type, user-agent, x-csrftoken, x-requested-with
Access-Control-Max-Age: 86400
Vary: origin
Access-Control-Max-Age tells the browser how long to cache the preflight result. Browsers apply their own upper limit, so a very large value may get clamped.
CORS with credentials
By default a cross-origin fetch doesn't send cookies. With credentials: "include" it does, but for the script to read the response the server must meet two conditions: Access-Control-Allow-Credentials: true, and a specific origin in Access-Control-Allow-Origin, not *. With credentials, * in Allow-Headers and Allow-Methods doesn't act as a wildcard either.
This is where the most dangerous mistake is born: since * doesn't work, the developer simply reflects whatever Origin arrived:
# middleware.py: DON'T do this
class AllowEverythingCorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
origin = request.headers.get("Origin")
if origin:
# reflects ANY site and allows cookies: evil.example can now
# read /api/me/, card lists, balances of a logged-in user
response["Access-Control-Allow-Origin"] = origin
response["Access-Control-Allow-Credentials"] = "true"
return response
That can be worse than CSRF. With CSRF the attacker fires requests blind; here they can read the user's data, including the CSRF token in the response. So a misconfigured CORS setup also cancels out your CSRF protection.
Configuring Django properly
A typical setup: an SPA on app.example.uz, a Django API on api.example.uz, authentication via session cookie. Both mechanisms are needed here: CORS so the SPA can read responses, CSRF so nobody else can send requests on the user's behalf.
# settings.py (pip install django-cors-headers)
INSTALLED_APPS = [
# ...
"corsheaders",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"corsheaders.middleware.CorsMiddleware", # as high as possible, before CommonMiddleware
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
# CORS: who may READ our responses from JavaScript
CORS_ALLOWED_ORIGINS = [
"https://app.example.uz",
"https://admin.example.uz",
]
CORS_ALLOW_CREDENTIALS = True
CORS_URLS_REGEX = r"^/api/.*$"
# CSRF: whose state-changing requests we accept (scheme is required)
CSRF_TRUSTED_ORIGINS = [
"https://app.example.uz",
"https://admin.example.uz",
]
CSRF_COOKIE_DOMAIN = ".example.uz" # so JS on app.example.uz can read csrftoken
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = "Lax" # Django's default, written out on purpose
CSRF_COOKIE_SAMESITE = "Lax"
# Only if your reverse proxy always sets/overwrites this header
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
Since Django 4.0, CSRF_TRUSTED_ORIGINS requires the scheme (https://...); the https://*.example.uz form for subdomains is also supported. CSRF_COOKIE_DOMAIN is needed because JavaScript on app.example.uz can't read a cookie set by api.example.uz.
One endpoint is enough for the SPA to get its CSRF cookie on startup:
# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_GET
@require_GET
@ensure_csrf_cookie
def csrf_bootstrap(request):
# The SPA calls this once on startup; Django sets the csrftoken cookie.
return JsonResponse({"detail": "ok"})
The frontend side:
function getCookie(name) {
const m = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
return m ? decodeURIComponent(m[1]) : null;
}
await fetch("https://api.example.uz/api/csrf/", { credentials: "include" });
const res = await fetch("https://api.example.uz/api/transfer/", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": getCookie("csrftoken"),
},
body: JSON.stringify({ to: "8600123412341234", amount: 50000 }),
});
If you use DRF, SessionAuthentication enforces CSRF for logged-in users by itself. Token or JWT authentication via the Authorization: Bearer header doesn't need CSRF, because the browser never adds that header on its own. Store the JWT in a cookie, though, and the CSRF problem comes right back.
# settings.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
# cookie-based: DRF enforces CSRF for session-authenticated users
"rest_framework.authentication.SessionAuthentication",
# header-based (Authorization: Bearer ...): browser never adds it on its own
"rest_framework_simplejwt.authentication.JWTAuthentication",
],
}
Production pitfalls
- "Origin checking failed" behind a proxy. Nginx terminates TLS and forwards to Django over HTTP.
request.is_secure()returnsFalse, Django expectshttp://api.example.uz, the browser sendshttps://.... The fix isSECURE_PROXY_SSL_HEADER, but only if your proxy always sets or overwrites that header. If the Host is rewritten too, you may needUSE_X_FORWARDED_HOST. CORS_ALLOW_ALL_ORIGINS = Truetogether withCORS_ALLOW_CREDENTIALS = True. Since*isn't allowed with credentials, django-cors-headers reflects the request's origin in that case. You end up with exactly the "allow everyone" middleware above.- Unanchored regexes.
r"https://.*example\.uz"inCORS_ALLOWED_ORIGIN_REGEXESalso matcheshttps://example.uz.evil.comandhttps://notexample.uz. Use^and$, and escape the dots. - The
nullorigin. Sandboxed iframes,file://pages and some redirects sendOrigin: null. Never put it on the allow list. - Middleware order. If
CorsMiddlewaresits belowCommonMiddleware, responses produced by middleware above it (anAPPEND_SLASHredirect, for example) go out without CORS headers. And preflight doesn't follow redirects at all. - "CORS error" hides the real error. If a 500 or 404 response has no CORS headers, the console shows only a CORS failure. Look for the real status in the Network tab.
- Caching and
Vary: Origin. IfAccess-Control-Allow-Origindepends on the origin and a CDN or proxy caches the response withoutVary: Origin, one origin's header can be served to another. - Webhooks. Callbacks from payment providers like Click and Payme are server-to-server requests with no cookies, so
@csrf_exemptis correct there. But a signature or secret check must take its place. CSRF_COOKIE_HTTPONLY = True. As the Django docs point out, this offers little practical benefit: the token is in the page anyway, JavaScript just has to read it from the DOM instead of the cookie.- Login CSRF. The login form must be protected too. Otherwise an attacker logs the user into the attacker's own account, and any card details the user enters end up there. Django's
LoginViewis protected by default.
Checklist
- Anything that changes state goes through POST/PUT/PATCH/DELETE only; GET changes nothing.
CsrfViewMiddlewareis on;@csrf_exemptonly on signature-verified webhooks.- Session and CSRF cookies are
SecureandSameSite=Lax(orStrict). CSRF_TRUSTED_ORIGINSlists exact origins, with scheme.CORS_ALLOWED_ORIGINSis an explicit list; neverCORS_ALLOW_ALL_ORIGINSwith credentials.CorsMiddlewareis as high as possible;CORS_URLS_REGEXcovers only the API.SECURE_PROXY_SSL_HEADERis set correctly behind a proxy.- Bearer-token APIs don't need CSRF; cookie-based APIs do.
- Test it: POST to the endpoint from a plain HTML form on another domain and confirm you get a 403.
Takeaway
CSRF and CORS don't replace each other. CSRF protection guards the server against foreign requests sent in the user's name; CORS tells the browser which sites may read your responses. Disabling CSRF or allowing any origin to make a 403 go away isn't a fix, it's a hole. The right path is an explicit origin list, SameSite cookies, and leaving Django's middleware alone.
// comments
Loading comments...