How to explicitly set samesite=None on a flask response How to explicitly set samesite=None on a flask response flask flask

How to explicitly set samesite=None on a flask response


Once the fix to this issue isreleased, you will be able to useset_cookie()like this:

from flask import Flask, make_responseapp = Flask(__name__)@app.route('/')def hello_world():    resp = make_response('Hello, World!');    resp.set_cookie('same-site-cookie', 'foo', samesite='Lax');    resp.set_cookie('cross-site-cookie', 'bar', samesite='Lax', secure=True);    return resp

While you're waiting for the release, you can stillset the headerexplicitly:

from flask import Flask, make_responseapp = Flask(__name__)@app.route('/')def hello_world():    resp = make_response('Hello, World!');    resp.set_cookie('same-site-cookie', 'foo', samesite='Lax');    # Ensure you use "add" to not overwrite existing cookie headers    resp.headers.add('Set-Cookie','cross-site-cookie=bar; SameSite=None; Secure')    return resp


You can also use the following code to set cookies with SameSite=None until fix is released

from werkzeug.http import dump_cookie# That's a workaround for explicitly setting SameSite to None# Until the following fix is released: # https://github.com/pallets/werkzeug/issues/1549def set_cookie(response, *args, **kwargs):    cookie = dump_cookie(*args, **kwargs)    if 'samesite' in kwargs and kwargs['samesite'] is None:        cookie = "{}; {}".format(cookie, b'SameSite=None'.decode('latin1'))    response.headers.add(        'Set-Cookie',        cookie    )