Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ( set_no_cache method) Cannot disable browser caching in Safari and Opera

After using Devise for my authentication, I found that there was a security hole in that, after the user logs out, the session variables are preserved. This allows anyone to press the back button and access the logged in user's previous screen.

I looked at these posts Num 1 Num 2 Num 3

I added these lines to my 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

In the _form.html.erb I added this at the top

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

Then I tested the application on Firefox, Chrome and Safari.

Firefox and Chrome were fine in that I logged out and hit the back button and could not see the previous screen of the user, however, in Safari and Opera, the insecure behavior persists. This code does not have an effect.

Any suggestions on how to fix this?

Thanks

like image 614
banditKing Avatar asked May 24 '12 19:05

banditKing


2 Answers

I faced the same problem and found a good solution and I blogged it to

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

To add ‘no-cache’, add the following lines @ the application_controller.rb file

before_filter :set_no_cache

and the function

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
like image 89
Kathirvel K G Avatar answered Oct 20 '22 16:10

Kathirvel K G


First of all, for any issues with cache, use Mark Nottingham's guide on HTTP caching

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

Try this.

like image 43
karlcow Avatar answered Oct 20 '22 16:10

karlcow