From February 17, 2020, if I lived on Chrome 80 without knowing that the default value of the Same-Site attribute would change from None to Lax, I was impatient with a problem on the production site. So, when I was looking for a way to set the Same-Site attribute for cookies in Django, there was a difference in the settings between Django 2 and 3, so I'd like to make a note of it.
The easy way is to use the package.
I'm still using Django2, and the package django-cookies-samesite
seemed useful, so I decided to use it to set the Same-Site attribute.
https://pypi.org/project/django-cookies-samesite/
It's easy to set up, just add it to MIDDLEWARE_CLASSES and define the variables in the config file.
MIDDLEWARE_CLASSES = (
'django_cookies_samesite.middleware.CookiesSameSite',
...
)
SESSION_COOKIE_SAMESITE = 'None'
It is also convenient because it has an option to set the cookie name and forcibly rewrite the SAMESITE of all cookies.
If you add it yourself, it will look like this. This is also easy, but it can be a bit annoying if you set cookies in various places.
response = HttpResponse('OK')
response.cookies[key]['samesite'] = 'None'
In Django3, the existing set_cookie has been improved so that you can pass a samesite. This is a lot cleaner.
response = HttpResponse('OK')
response.set_cookie(key, value, secure=True, samesite='None')
However, unlike Django2, it is not a process in Middleware, so it may be troublesome that you have to set it one by one.
I don't have a habit of closing chrome so much, so it was hard to notice this problem in my environment, but the fix itself was relatively easy.
Recommended Posts