Y
Y
Yaroslav2021-02-09 23:23:13
HTTP Cookies
Yaroslav, 2021-02-09 23:23:13

Why is Flask ignoring SESSION_COOKIE_SAMESITE?

For some reason, Flask is ignoring the SESSION_COOKIE_SAMESITE config option, although it seems like it should handle it ( link )

$ curl -I http://localhost:5000/
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 5
Set-Cookie: foo=bar; Secure; HttpOnly; Path=/; SameSite=Strict
Set-Cookie: session=1e70123c-2726-44f7-9e6e-b9e5a083699d; Expires=Wed, 10-Feb-2021 20:04:03 GMT; HttpOnly; Path=/
Server: Werkzeug/1.0.1 Python/3.7.3
Date: Tue, 09 Feb 2021 20:04:03 GMT


It can be seen that two cookies are set, I set one (foo) manually and any of its parameters are processed - everything is OK with it. The other one (session) is set by Flask ignoring the option SESSION_COOKIE_SAMESITEfor some reason.

The code has been simplified to a minimum:
#!/usr/bin/env python3
from flask import Flask, Response
from flask_session import Session

app = Flask(__name__)
app.config.update(
    FLASK_ENV = 'development',
    SESSION_TYPE = 'redis',
    SESSION_COOKIE_SAMESITE = "Strict",
    PERMANENT_SESSION_LIFETIME = 86400,
)

sess = Session()
sess.init_app(app)

@app.route('/')
def index():
    response = Response('hello')
    response.set_cookie('foo', 'bar', secure=True, httponly=True, samesite='Strict')
    return response


If you play with other parameters (set SESSION_COOKIE_SECUREor increase PERMANENT_SESSION_LIFETIME) - then their changes are reflected in the cookie, but SESSION_COOKIE_SAMESITEsimply ignored for some reason. Cookies are created in redis. Even if you change SESSION_TYPE = 'filesystem' - cookies are sent, but still without the samesite.

What am I doing wrong? How can I get around this and set the samesite attribute for the session cookie?

Modules (virtualenv):
cachelib==0.1.1
click==7.1.2
Flask==1.1.2
Flask-Session==0.3.2
itsdangerous==1.1.0
Jinja2==2.11.3
MarkupSafe==1.1.1
pkg-resources==0.0.0
redis==3.5.3
Werkzeug==1.0.1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yaroslav, 2021-02-10
@xenon

Figured it out myself. The current version of Flask-Session (0.3.2) basically doesn't know about samesite, and uses code like this to set cookies:

response.set_cookie(app.session_cookie_name, session_id,
                            expires=expires, httponly=httponly,
                            domain=domain, path=path, secure=secure)

Very simple changes to the code are required, Pull requests are already there, but the maintainer has not accepted them yet. I made my fork, put:
pip install git+https://github.com/yaroslaff/[email protected]

For a while, it'll do. When the maintainer accepts the pull-requests, it will be possible to return to the original project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question