[PYTHON] Same-Site attribute setting for cookies in Django

background

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.

For Django2

When using a package

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.

Add your own samesite

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'

For Django 3

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.

the end

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

Same-Site attribute setting for cookies in Django
Get query parameters for GET requests in Django
Models in Django
Django 1.9 for internationalization
Do an ambiguous search for mysql in Django
Forms in Django
Learning notes for the migrations feature in the Django framework (2)
List method for nested resources in Django REST framework
Learning notes for the migrations feature in the Django framework (3)
Learning notes for the migrations feature in the Django framework (1)
Model changes in Django
Summary of stumbling blocks in Django for the first time
Best practices for dynamically handling LINE Flex Messages in Django