This one took me a while to debug. When upgrading my existing application to Rails 3 almost everything was working fine except whenever I would click the Logout link I would get an error because Rails couldn’t verify that the UserSessionsController#destroy request was valid from my app.
This is the error message shown:
ActionController::InvalidAuthenticityToken in User sessionsController#destroy
actionpack (3.0.0) lib/action_controller/metal/ request_forgery_protection.rb:96:in `verify_authenticity_token'
And the solution is simple, you just need to add the new csrf_meta_tag helper to your generated page (probably in the /views/layouts/application.html.erb file).
... <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title>Some Title</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> </head> ...
Line 7 is the one you care about and need to have in your html.erb file.
This helper includes the appropriate meta tags which make the authenticity_token available to the handleMethod javascript function. In Rails3, links generated with the link_to helper which use a :method other than GET get passed through that handleMethod function in rails.js. That function creates a temporary form, sets some parameters and submits it. And if you’re using protect_from_forgery (you should be) all non-GET requests are checked to prevent Cross Site Request Forgery (CSRF). So, if those meta tags don’t exist on your page, the handleMethod function doesn’t know what your authenticity_token is, and the request will be rejected with the error above.
Line 5 below is an example of my main nav logout link that was causing the problem when clicked. No change was required to this code after doing the above fix.
<% if !current_user %> <%= link_to "Log In", new_user_session_path %> | <%= link_to "Register", new_account_path %> | <% else %> <%= link_to "Logout", user_session_path, :method => :delete %> | <% end %>
This isn’t specific to Authlogic’s logout click – any time you are using link_to now in Rails3 with non-GET methods, it uses unobtrusive javascript. And if you’re missing the csrf_meta_tag helper, any unobtrusive javascript posts will fail to validate.
- BROWSE / IN TIMELINE
- « Running Rails 3 using RVM
- » Upgrading your Authlogic Gem for Rails3
- BROWSE / IN ruby on rails
- « Running Rails 3 using RVM
- » Upgrading your Authlogic Gem for Rails3
SPEAK / ADD YOUR COMMENT
Comments are moderated.
