【发布时间】:2020-01-23 00:20:32
【问题描述】:
On February 4th 2020,Google Chrome 将要求将SameSite=None; 添加到所有跨站点 cookie。 Rails 6.1 and soon Rails 6.0 have added a same_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。
This StackOverflow answer 展示了一种可以修改 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 中?
【问题讨论】:
标签: ruby-on-rails cookies middleware rack samesite