3

I have a very specific question that I haven't found within the many questions regarding this topic.

Initially my Set-Cookie headers were blocked. I managed to resolve that, but the Cookies are still not stored and I have no clue as to why.


I have a DRF + React web application which I recently changed from Token Authentication to Session Authentication for server side expiration. In production this works great, upon login I receive two Set-Cookies, a session id and a csrftoken. However, in my development environment, the Set-Cookies are blocked as This Set-Cookie was blocked because it had the 'SameSite=Lax' attribute but came from a cross-site response which was not the repsonse to a top-level navigation..

  • I tried changing the SameSite setting to none, in which case Chrome requires secure cookies, which I don't think is possible in my dev environment.
  • I tried disabling Cookies without SameSite must be secure in chrome://flags.
  • Listing 127.0.0.1 in CORS_ALLOWED_ORIGINS allows Set-Cookie, but somehow an old cookie is set. This does not work for localhost.
  • Although I don't think this is relevant, a lot of solutions here mention to add {withCredentials: true} to the requests, this however does not solve my issue as I do receive the Set-Cookie headers, they're just blocked.
  • If I log in on 127.0.0.1, I get a 403 with CSRF missing or incorrect. It is listed in CSRF_TRUSTED_ORIGINS and I do not get this on localhost.

Cookie/CORS related Settings.py

# CSRF / CORS / Cookies
ALLOWED_HOSTS = ['*']
CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:3000',
    'http://localhost:3000', 
]
CSRF_TRUSTED_ORIGINS = [
    'http://localhost:3000',
    'http://127.0.0.1:3000',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_USE_SESSIONS = False
CSRF_COOKIE_HTTPONLY = False         # Not accessible by client (not important)
CSRF_COOKIE_AGE = 8 * 3600           # Expires after 8 hr
CSRF_COOKIE_SECURE = False           # Only HTTPS

SESSION_COOKIE_HTTPONLY = False      # Not accessible by client 
SESSION_COOKIE_AGE = 8 * 3600        # Expires after 8 hr
SESSION_COOKIE_SECURE = False        # Only HTTPS

1 Answer 1

1

Eventually I found the solution, which contains two parts:

  1. Make sure Set-Cookie headers aren't blocked by adding 'http://127.0.0.1:3000' to CORS_ALLOWED_ORIGINS.
  2. Ensure no old cookies are in the browser during login, so that you can login with the tag {withCredentials: true}. The CSRF check will fail with old/invalid cookies. However, with the check set to false, the new cookies aren't stored.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.