skip to Main Content

I am using react as frontend and using django for backend.
When I host both the frontend and backend on localhost, everything works fine and X-CSRFTOKEN is sent perfectly.

const instance = axios.create({
    withCredentials: true,
    withXSRFToken: true,
    xsrfHeaderName : 'X-CSRFTOKEN',
    xsrfCookieName : 'csrftoken'
});

My DJango settings are (taken from this answer Django – check cookies's "SameSite" attribute):

CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = "None"
SESSION_COOKIE_SAMESITE = "None"

but when my frontend (firebase )and backend(eks aws) are hosted on different subdomains, I receive a 403 Forbidden Error.
Edit:

CORS_ALLOWED_ORIGINS = ["http://localhost:3000", "https://app.example.com"]

CSRF_TRUSTED_ORIGINS = [
    "http://localhost:3000",
    "https://app.example.com",
]

It should return a 201 ccreated response but instead it is returning a 403 error, CSRF verification failed. Request aborted.

2

Answers


  1. Chosen as BEST ANSWER

    The issue above was that when I inspected the cookies, the domain for csrf cookie was backend.app.com, and the frontend was hosted at frontend.app.com. So I added this setting to my django settings module and everything worked fine:

    CSRF_COOKIE_DOMAIN = ".app.com"
    

  2. Add your domain name to CSRF_TRUSTED_ORIGINS = ['https://yourdomain.com'] in settings.py

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search