简体   繁体   中英

InvalidAuthenticityToken after Devise login/logout in another tab

I have some problems with the InvalidAuthenticityToken exception when changing user authentication state in different tabs.

My app is quite simple. In fact, just a basic learning app for my studies. https://github.com/antonkoh/railsrep/tree/master/lesson17/my_app

It uses Devise gem for authentication:

 <%= link_to "Sign out", destroy_user_session_path, method: :delete %>

 <%= link_to "Sign in", new_user_session_path %>

protect_from_forgery is set to :exception as it is a browser app, nothing API related yet.

I do have <%= csrf_meta_tags %> specified in my layout.

The problem is reproduced in many different ways. Just a couple general examples:

  1. On tab AI open a form to add/edit a post as an anonymous user.
  2. On tab BI sign in as any user.
  3. Back on tab AI try to add the post Result: InvalidAuthenticityToken

or

  1. On tab AI open a list of posts as a signed-in user.
  2. On tab BI sign out.
  3. Back on tab AI try to destroy a post. Result: InvalidAuthenticityToken

I have introduced my own means to make sure that certain actions are available to certain signed-in users, but I don't even get to see them in action because of this exception. Is it supposed to work this way, just throwing itself at any PATCH request from an unrefreshed page after user authentication state change? Will my application become less secure if I change forgery protection mode to null_session or reset_session?

Thank you very much

This is normal and expected. You need to understand What are sessions?

In your app, sessions store in cookies. browser tabs share cookies. It's the same if you open a browser window via another.

For security reason, session should be reset after login/logout. Devise is just doing his job.

Once session is reseted, the old CSRF token is no longer valid. Thats why when you submit a POST request from the old tab, it raise InvalidAuthenticityToken.

For user experience, you can rescue InvalidAuthenticityToken error in controller, then redirect the user to a new page, or reload the page for the user with an error message.

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM