Webapp2 Python set_cookie 不支持samesite cookie?

Webapp2 Python set_cookie does not support samesite cookie?

webapp2 documentation there is no mention of setting the SameSite attribute for a cookie, it seems to be built on the response handler from WebOB, I checked webOB doc page it clearly shows the 'SameSite' flag as an accepted cookie parameter

我尝试在 set cookie 中设置它:

self.response.set_cookie(name, secure_cookie, path='/', secure=True,
httponly=True, samesite='lax', expires=expireDate)

但我收到以下错误:

TypeError: set_cookie() got an unexpected keyword argument 'samesite'

我知道可以使用 self.response.headers.add_header('Set-Cookie', ... 但我希望我可以按照 webapp2 文档

使用 self.response.set_cookie

Samesitewebob 1.8 but The App Engine Standard Environment SDK ships with 1.1.1 and 1.2.3 中作为 built-in 库引入。

您可以在较新的 webob 中尝试 vendoring,看看这是否会覆盖 built-in 版本。

安装支持 samesitewebob 版本后,可以将 samesite 关键字参数传递给 Response.set_cookie

class MyHandler(webapp2.RequestHandler):
    def get(self):
        self.response.set_cookie('cookie-name', value='42', samesite='lax')

此示例应用程序在 webapp2_extras.sessions 生成的 session cookie 上设置 samesite=strict,假设基础 webob 包支持它。

import webapp2
from webapp2_extras import sessions


class HelloHandler(webapp2.RequestHandler):
    def dispatch(self):
        self.session_store = sessions.get_store(request=self.request)
        try:
            super(HelloHandler, self).dispatch()
        finally:
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        return self.session_store.get_session()

    def get(self):
        self.session['hello'] = 'world'
        self.response.headers['content-type'] = 'text/plain'
        self.response.write('Hello world')


webapp2_config = { 
    'webapp2_extras.sessions': {
        'secret_key': 's3cr3t',
        'cookie_args':{'samesite': 'strict'}
    },  
}

application = webapp2.WSGIApplication([
    webapp2.Route(r'/', handler=HelloHandler),
],
    config=webapp2_config)

响应的set-cookieheader是

session=eyJoZWxsbyI6IndvcmxkIn0=|1595151290|09b22484901689e6eb0411792c8732ef134d2b66; Path=/; SameSite=strict

我通过 header 更改解决了这个问题,没有安装任何外部库。只需在设置 cookie 后使用此功能:

def AddSameSiteToCookies(self):
    for index, header in enumerate(self.response.headers._items):
        if header[0] == "Set-Cookie" and "SameSite" not in header[1]:
            temp = list(header)
            temp[1] = temp[1].replace("Path=", "SameSite=Lax; Path=")
            self.response.headers._items[index] = tuple(temp)