2020 年 2 月 4 日,Google Chrome 将需要SameSite=None;
添加到所有跨站点 cookie。 Rails 6.1 和即将发布的 Rails 6.0same_site: :none
为 rails cookie 哈希添加了一个选项:
cookies["foo"]= {
value: "bar",
expires: 1.year.from_now,
same_site: :none
}
但较旧的 Rails 5.x 应用程序不会获得升级以访问same_site
选项哈希。我知道SameSite=None;
cookie 选项可以手动添加到控制器中的 Rails 使用:
response.headers["Set-Cookie"] = "my=cookie; path=/; expires=#{1.year.from_now}; SameSite=None;"
但是我的 Rails 5.x 应用程序使用复杂的 cookie 对象来修改 cookie。我不想将它们分开,而是想编写 Rack 中间件来SameSite=None;
一次手动更新所有带有该属性的 cookie。
这个 StackOverflow 答案显示了一种可以修改 cookie 以更新机架中间件中的 cookie 的方法:
# 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)
如何重新编写此机架中间件代码以手动附加SameSite=None;
到每个现有的 cookie 中?