How to handle pages with legacy CSRF authentication tokens in Rails

In our Rails application, users are usually encouraged to open multiple browser tabs within hours or days. The problem occurs when on one of these tabs the user logs out, then returns to the system (or the session expires and a new session is created).

This causes CSRF authentication tokens on all other tabs to become invalid. If they try to submit some form or make any ajax request on these tabs without updating, they will receive an error message (and actually log out, because this is the default Rails behavior when an odd authentication token is passed).

This behavior is clearly undesirable. I was wondering what people are doing to gracefully handle situations where the user has a window open for your site, but the authenticity token has expired.

What I do not want to do is just redirect them to the login page, because then they can lose their job if, for example, they write a long blog post or something like that.

The solution that comes to mind is to have some javascript that either polls the server to check if the authentication token has changed or polls the user's cookies to check if the session has changed. I never heard of any of them doing, so I wanted to see what the community was thinking.

+6
source share
2 answers

First: the entry / exit / in will not lead to the appearance of a new csrf token. It will still be stored in the user's cookie. The next time he logs in through the same browser, he will receive the same token.

In the latest versions of Rails, in case of an incorrect token, no errors will occur: all Rails - just resets the session before passing it to the controller.

So, upgrade Rails and you will get less pain.

+3
source

Are you sure you mean the CSRF token, not the token? It makes no sense to redirect the login to the CSRF token mismatch. You just ask the user to repeat everything that he tried to do. (In a traditional web application, this usually appears when submitting a form, you can consider the CSRF mismatch as a validation error and show the form again, saving all field values ​​and requesting the user to retransmit. In more AJAX - a heavy application, you can use which this is a common CSRF flag, and if it is set, ask the user to do everything he has done (click a button, etc.) again, or even automate all this without disturbing the user.

+3
source

Source: https://habr.com/ru/post/914925/


All Articles