Search code examples
pythonpython-3.xcookiestornadosamesite

tornado using RequestHandler.set_secure_cookie() doesn't allow adding samesite attribute


In my python backend application, I'm trying to set a secure cookie with the valid tornado attributes.

However, I had a veracode issue saying that I need to set the attribute samesite=strict.

Doing as follows:

    # this line is called from another method that sets the cookie.
    request_handler.set_secure_cookie(**self.build_cookie())



    def build_cookie(self):
        cookie_info = {
            'name': 'session_cookie',
            'value': 'session_cookie_value',
            'httponly': True,
            'expires_days': None,
            'samesite': 'Strict',
            'secure': True,
        }
        return cookie_info

gives me the following error

File "/usr/local/lib/python3.6/http/cookies.py", line 332, in __setitem__
raise CookieError("Invalid attribute %r" % (K,))
http.cookies.CookieError: Invalid attribute 'samesite'

Does anyone have an idea how to set this attribute?


Solution

  • Support for cookie attributes depends on the version of Python; the samesite attribute was added in Python 3.8. You can also monkey-patch it in older version of python as described in this question.