【问题标题】:Setting the samesite-Attribute for CherryPy's sessions为 CherryPy 的会话设置相同的站点属性
【发布时间】:2020-09-01 08:19:27
【问题描述】:

我正在使用 CherryPy 编写软件。我正在使用普通会话,使用“cherrypy.session”。 现在我注意到 Firefox 抱怨我使用了“错误的”samesite-Attribute,并且将来可能不再可用。

有没有办法将 CherryPy 的 session-cookies 的 samesite-Attribute 设置为另一个值?

【问题讨论】:

    标签: python cookies cherrypy


    【解决方案1】:

    这有点棘手,因为已经讨论过好几次了(例如,看here) 这意味着对于 python

    1. 打开 ../python3.x/site-packages/cherrypy/_cprequest.py

    2. 在文件开头添加如下代码

       from http import cookies
       cookies.Morsel._reserved.setdefault('samesite', 'SameSite')
      
    3. 关闭并保存

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

    5. 更改以下函数定义

      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):
      

        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. 更改以下内容:

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

    到:

         set_response_cookie(path=path, path_header=path_header, name=name,
                         timeout=cookie_timeout, domain=domain, secure=secure,
                         httponly=httponly,samesite=samesite)
    
    1. 更改以下内容:

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

    到:

    def set_response_cookie(path=None, path_header=None, name='session_id',
           timeout=60, domain=None, secure=False, httponly=False,samesite='lax'):
    
    1. 将此代码添加到 set_response_cookie() 方法的末尾:

       if samesite in ['lax', 'strict', None]:
           cookie[name]['samesite'] = str(samesite)
      
    2. 保存文件并关闭它。

    现在在您的代码(驱动程序)中,您可以像这样使用“samesite”属性:

    'tools.sessions.samesite': 'strict'
    

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

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-05
      • 2020-02-21
      • 2011-07-31
      • 2012-01-30
      • 1970-01-01
      • 2022-01-18
      • 2021-08-31
      • 2015-11-16
      相关资源
      最近更新 更多