Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle pages with stale CSRF authenticity tokens in Rails

In our Rails application, it is common for users to keep multiple browser tabs open for hours or days at a time. The problem occurs when in one of these tabs, the user logs out then logs back in (or the session expires and a new session is created).

This causes the CSRF authenticity tokens on all the other tabs to become invalid. If they try to submit any form or make any ajax request on those tabs without refreshing, they will get an error (and in fact get logged out because that is the default Rails behavior when a bad authenticity token is passed).

This behavior is clearly undesirable. I was wondering what people do to gracefully handle situations where a user has a window open to your site but the authenticity token is out of date.

What I don't want to do is just redirect them to the login page, because then they might lose their work, if for example they have been writng a long blog post or something.

The solution that comes to mind is to have some javascript that either polls the server to check whether the authenticity token has changed, or polls the user's cookies to check whether the session has changed. I have never heard of anyone doing either of these, so I wanted to see what the community thought.

like image 936
Jacob Avatar asked May 04 '12 18:05

Jacob


1 Answers

First of: logging in/out/in won't lead to appearing a new csrf-token. It still will be saved in the user's cookie. Next time it logs in via the same browser it'll get the same token.

In latest versions of Rails no errors will be thrown in the case of incorrect token: all the Rails does -- just resets the session before passing it to a controller.

So, update your Rails and you'll get one pain less.

like image 180
jdoe Avatar answered Sep 28 '22 07:09

jdoe