On February 4th 2020,Google Chrome浏览器将要求将SameSite=None;
添加到所有跨站点Cookie中。 Rails Cookie哈希的Rails 6.1 and soon Rails 6.0 have added a same_site: :none
选项:
same_site: :none
但是较旧的Rails 5.x应用程序将无法获得升级,无法访问cookies["foo"]= {
value: "bar",
expires: 1.year.from_now,
same_site: :none
}
选项哈希。我知道可以使用以下命令在控制器中手动将same_site
cookie选项添加到Rails:
SameSite=None;
但是我的Rails 5.x应用程序使用复杂的cookie对象来修改cookie。除了将它们分开,我想编写Rack中间件来一次手动更新具有response.headers["Set-Cookie"] = "my=cookie; path=/; expires=#{1.year.from_now}; SameSite=None;"
属性的所有cookie。
[SameSite=None;
显示了一种可修改Cookie的方法,以更新Rack Middleware中的Cookie:
This StackOverflow answer
# lib/same_site_cookie_middleware
class SameSiteCookieMiddleware
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
# confusingly, response takes its args in a different order
# than rack requires them to be passed on
# I know it's because most likely you'll modify the body,
# and the defaults are fine for the others. But, it still bothers me.
response = Rack::Response.new body, status, headers
response.set_cookie("foo", {:value => "bar", :path => "/", :expires => 1.year.from_now, same_site: :none})
response.finish # finish writes out the response in the expected format.
end
end
如何重新编写此机架中间件代码,以将# application.rb
require 'same_site_cookie_middleware'
config.middleware.insert_after(ActionDispatch::Cookies, SameSiteCookieMiddleware)
手动附加到每个现有的cookie中?
我能够使它与以下对象一起使用:
SameSite=None;
并通过以下方式添加到中间件:
#Append SameSite=None to all cookies as long as it was not provided
class SameSiteCookies
HTTP_HEADER = 'Set-Cookie'.freeze()
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
if headers[HTTP_HEADER] && !(headers[HTTP_HEADER] =~ /SameSite\=/)
headers[HTTP_HEADER] << ';' if !(headers[HTTP_HEADER] =~ /;$/)
headers[HTTP_HEADER] << ' SameSite=None'
end
[status, headers, body]
end
end