Skip to content
Cross-site cookies setup problem
zeck3
OP

a year ago

I have problem setting up cookies for cross site domains:

frontend staging:

ucap-fs.up.railway.app

backend staging:

ucap-bs.up.railway.app

Tech stack:

Django, Rest Framework

React + Vite, Axios

When I login successful, I can't proceed to any post requests, always show 403 forbidden. I have the following setup in django settings.py:

ALLOWED_HOSTS = ["ucap-bs.up.railway.app"]
CORS_ALLOWED_ORIGINS = ["https://ucap-fs.up.railway.app"]
CSRF_TRUSTED_ORIGINS = ["https://ucap-fs.up.railway.app"]

CORS_ALLOW_CREDENTIALS = True
SESSION_COOKIE_SAMESITE = "None"
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_PARTITIONED = True

CSRF_COOKIE_SAMESITE = "None"
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_PARTITIONED = True

USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

Axios Client setup:

const axiosClient = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  withCredentials: true,
  withXSRFToken: true,
  xsrfCookieName: "csrftoken",
  xsrfHeaderName: "X-CSRFToken",
});

When I log in Cookies show (no sessionid):

https://ucap-fs.up.railway.app > csrftoken > value: q49EebR7XFC2HiiKy5UWMWJDqdnwyOPz, domain: ucap-bs.up.railway.app

csrf/ 200 ok:

Response headers:

set-cookie csrftoken=2m1C5noKaHHbiu0Xmawnv8OHEZxD7QWW; expires=Sun, 22 Nov 2026 04:15:35 GMT; Max-Age=31449600; Partitioned; Path=/; SameSite=None; Secure

Request headers:

cookie csrftoken=eFf1cQZ0QGOCsxtU1Rt5f6oJbUGWktp2; csrftoken=2m1C5noKaHHbiu0Xmawnv8OHEZxD7QWW

login/ 200 ok

Response headers:

set-cookie: csrftoken=iT6H2JLu04xp1N9PGekddYDaBxVIILFC; expires=Sun, 22 Nov 2026 04:15:36 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure

set-cookie: sessionid=g6xwh01rvqzez1m65fkdcu1tjcrsx774; expires=Sun, 23 Nov 2025 04:30:36 GMT; HttpOnly; Max-Age=900; Path=/; SameSite=None; Secure

Request headers:

cookie: csrftoken=2m1C5noKaHHbiu0Xmawnv8OHEZxD7QWW; csrftoken=2m1C5noKaHHbiu0Xmawnv8OHEZxD7QWW

$10 Bounty

2 Replies

Railway
BOT

a year ago

Hey there! We've found the following might help you get unblocked faster:

If you find the answer from one of these, please let us know by solving the thread!


soundcake

14 days ago

Your frontend and API use different hostnames. A host-only csrftoken set by the API is not readable through the frontend's document.cookie. Axios's withXSRFToken enables its cookie-reading path; it doesn't let that path read another hostname's cookie.

Return Django's token in the response body, and send it explicitly with requests to your API:

from django.http import JsonResponse
from django.middleware.csrf import get_token
from django.views.decorators.cache import never_cache

@never_cache
def csrf(request):
    return JsonResponse({"csrfToken": get_token(request)})
const api = axios.create({ baseURL: API_BASE_URL, withCredentials: true });
const { data } = await api.get('/csrf/');
await api.post('/auth/login/', credentials, {
  headers: { 'X-CSRFToken': data.csrfToken },
});
// Django login rotates the token. Get the replacement before the next POST.
const { data: fresh } = await api.get('/csrf/');
await api.post('/your-write-endpoint/', payload, {
  headers: { 'X-CSRFToken': fresh.csrfToken },
});

Keep CsrfViewMiddleware, the exact trusted frontend origin, credentialed CORS, and secure cookies. Django's CSRF reference documents both get_token() and login-time rotation. Axios reads tokens from document.cookie.

Your missing sessionid has a second clue: the /csrf response has Partitioned, while the login response's cookies don't. Check the browser's blocked-cookie reason on that login response, and make the actual session and CSRF Set-Cookie attributes consistent with the cookie strategy you use. Confirm that your installed Django version or cookie middleware supports the partition settings; the emitted headers are what the browser receives. The JSON token change cannot make a browser accept a rejected session cookie.

The token flow above passes seven local Django 5.2 tests, including login rotation and rejection of an untrusted origin. The login response's blocked-cookie reason is still needed to identify its storage failure.

Prepared with AI assistance.


Welcome!

Sign in to your Railway account to join the conversation.

Loading...