I am trying to set a specific cookie to have samesite='None' for a Django project on version 2.2.x. I continue to get the below error.
raise ValueError('samesite must be "lax" or "strict".')
which I can see is coming from venv/lib/python3.9/site-packages/django/http/response.py
if samesite:
if samesite.lower() not in ('lax', 'strict'):
raise ValueError('samesite must be "lax" or "strict".')
self.cookies[key]['samesite'] = samesite
I have tried to following:
- Set this globally in settings eg
CSRF_COOKIE_SAMESITE = 'None',SESSION_COOKIE_SAMESITE = 'None' - Setting this on the cookie that need it via
set_cookie(name, value=value, secure=True, samesite='None')
Both approaches don't work. I have also tried to installed the package django-cookies-samesite and adding its middleware, however it doesn't seem to make a difference.
# example
MIDDLEWARE = (
"django_cookies_samesite.middleware.CookiesSameSite",
# other middleware
)
When I set the value to None instead of 'None' no value is added and I believe Chrome falls back to lax when there isn't a value there.
I have also tried setting a cookie outside of the Django set_cookie without any luck:
# this fails with AttributeError: 'JsonResponse' object has no attribute 'COOKIES'
response["Set-Cookie"] = f"{name}={value}; Secure={False}; SameSite='None'; Path=/"
# this adds the cookie however doesn't parse it correctly so it fails
response.cookies[name] = f"{name}={value}; Secure={False}; SameSite='None'; Path=/"
# eg
Set-Cookie: my_name="my_value Secure=False\073 SameSite='None'\073 Path=/"
# where the other cookies look like
Set-Cookie: my_name=my_value; expires=Wed, 28 Apr 2021 02:51:02 GMT; Max-Age=2592000; Path=/
Is there a way around this? I can see the newer versions of Django support this however trying to see if there is a way to solve with the our current version of Django (2.2).