如何在cookie前缀中添加__Host或__Secure?

5
我正在尝试在rails 6.0.3应用程序中添加会话cookie的前缀,但无法找到方法来完成它。我已经尝试将密钥添加到会话存储的选项哈希中,但这并没有帮助,反而破坏了我的应用程序。我使用auth-logic gem进行身份验证,但没有找到优雅地完成它的方法,只能寄希望于有某种方法可以实现。

conf/initalizers/session_store.rb

opts = {}
if Rails.configuration.host == "myapplication.com"
  opts =  {expire_after: 2.months, domain: :all}
end

unless Rails.env.test?
  opts[:secure] = true
  opts[:same_site] = :none
end
opts[:key] = '__Host-'

Rails.application.config.session_store :active_record_store, **opts

这是Github Cookies的屏幕截图。我希望我的会话标头与图片中的相同(以__Host-为前缀)。

enter image description here

1个回答

1
根据您提供的链接...
带有__Host-前缀的Cookie必须具有路径为/(表示主机上的任何路径)并且不能具有域属性。
因此,我认为您需要删除“domain”属性并添加“path”。例如:
opts = {}
if Rails.configuration.host == "myapplication.com"
  opts =  {expire_after: 2.months}
end

unless Rails.env.test?
  opts[:secure] = true
  opts[:same_site] = :none
  opts[:path] = '/'
end
opts[:key] = '__Host-'

Rails.application.config.session_store :active_record_store, **opts

我使用这个解决方案时遇到了“ActionController :: InvalidAuthenticityToken:无法验证CSRF令牌的真实性。”错误。 - Guillaume
@Guillaume - 你需要提出自己的问题并提供相关信息。评论区不是合适的地方 :) - Fraser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接