问题 Rails(set_no_cache方法)无法在Safari和Opera中禁用浏览器缓存


在使用Devise进行身份验证后,我发现有一个安全漏洞,在用户注销后,会话变量被保留。这允许任何人按下后退按钮并访问登录用户的上一屏幕。

我查看了这些帖子 数字1 数字2 数字3

我将这些行添加到application_controller中

before_filter :set_no_cache
def set_no_cache
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end

在_form.html.erb中,我在顶部添加了这个

<%if user_signed_in? %>
<%=link_to "Sign Out",  destroy_user_session_path, :method => :delete %><br/>
<%= form_for(@listing) do |f| %>
<% if @listing.errors.any? %>
...........

然后我在Firefox,Chrome和Safari上测试了该应用程序。

Firefox和Chrome很好,因为我退出并点击了后退按钮,无法看到用户的上一个屏幕,但是,在Safari和Opera中,不安全的行为仍然存在。此代码没有效果。

对于如何解决这个问题,有任何的建议吗?

谢谢


1654
2018-05-24 19:37


起源

这是重复的 stackoverflow.com/questions/2866826/... - hallvors
哼。看着这个链接。不管它在哪里谈论Safari,它只提到Opera。我已经尝试了他们在那里列出的所有解决方案,如上所示。 - banditKing
Ops,你对Safari很正确。只有问题的“Opera”部分才真正重复,因为那里的回复解释了为什么Opera的行为如此,唯一真正的解决方法是使用https并且必须重新验证。 - hallvors
好的,非常感谢。我设法解决了Safari问题。但是对于Opera我会注意到你的建议。非常感谢 :) - banditKing
有谁知道如何在rails 3.2.20中这样做? stackoverflow.com/questions/26994714/... - equivalent8


答案:


我遇到了同样的问题,并找到了一个很好的解决方案,我在博客上写道

http://www.fordevs.com/2011/10/how-to-prevent-browser-from-caching-a-page-in-rails.html

要添加“no-cache”,请在application_controller.rb文件中添加以下行

before_filter :set_no_cache

和功能

def set_no_cache
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end

11
2018-03-22 08:06



这在Safari中不起作用,但在Chrome和Firefox中起作用。 - joeyk16


首先,对于缓存的任何问题,请使用Mark Nottingham HTTP缓存指南

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

尝试这个。


1
2018-06-08 19:04





我发现在我的应用程序控制器中执行此操作非常适合开发。

after_filter  :expire_for_development

protected

def expire_for_development
  expires_now if Rails.env.development?
end

0
2018-02-15 21:27