Daarin
Daarin

Reputation: 134

Setting the samesite-Attribute for CherryPy's sessions

I am programming a software using CherryPy. I am using the normal sessions, using 'cherrypy.session'. Now I noticed Firefox complaining I am using the "wrong" samesite-Attribute and that it possibly will not be available in the future anymore.

Is there a way to set the samesite-Attribute of the session-cookies for CherryPy to another value?

Upvotes: 1

Views: 477

Answers (1)

Sourena
Sourena

Reputation: 191

This is kind of tricky as already discussed several times (e.g., look here) This means that apparently there is no solution for python < 3.8. However, you can still use monkeypatch. So do the following to solve the problem:

  1. Open ../python3.x/site-packages/cherrypy/_cprequest.py

  2. Add the following codes at the beginning of the file

     from http import cookies
     cookies.Morsel._reserved.setdefault('samesite', 'SameSite')
    
  3. close and save it

  4. open ../python3.x/site-packages/cherrypy/lib/sessions.py

  5. change the following function definition

    def init(storage_type=None, path=None, path_header=None, name='session_id',
     timeout=60, domain=None, secure=False, clean_freq=5,
     persistent=True, httponly=False, debug=False,
     # Py27 compat
     # *, storage_class=RamSession,
     **kwargs):
    

to

    def init(storage_type=None, path=None, path_header=None,
      name='session_id',
      timeout=60, domain=None, secure=False, clean_freq=5,
      persistent=True, httponly=False,samesite='lax' debug=False,
      # Py27 compat
      # *, storage_class=RamSession,
      **kwargs):
  1. Change the following:

      set_response_cookie(path=path, path_header=path_header, name=name,
                      timeout=cookie_timeout, domain=domain, secure=secure,
                      httponly=httponly)
    

to:

     set_response_cookie(path=path, path_header=path_header, name=name,
                     timeout=cookie_timeout, domain=domain, secure=secure,
                     httponly=httponly,samesite=samesite)
  1. change the following:

    def set_response_cookie(path=None, path_header=None, name='session_id',
        timeout=60, domain=None, secure=False, httponly=False):
    

to:

def set_response_cookie(path=None, path_header=None, name='session_id',
       timeout=60, domain=None, secure=False, httponly=False,samesite='lax'):
  1. add this code to the end of the set_response_cookie() method:

     if samesite in ['lax', 'strict', None]:
         cookie[name]['samesite'] = str(samesite)
    
  2. save the file and close it.

Now in your code (driver) you can use the "samesite" attribute like this:

'tools.sessions.samesite': 'strict'

or

'tools.sessions.samesite': 'lax' # This is the default value

good luck!

Upvotes: 1

Related Questions