An Authentic Pain in the Ass

Posted by Ben Jackson Fri, 29 Aug 2008 03:42:17 GMT

Just figured out the answer to a problem which was driving me nuts. Consider the following code. Can you see what's wrong?


def register
  if logged_in?
    self.current_user.forget_me 
    cookies.delete :auth_token
    reset_session
  end
end

Neither could I. Even when the ActionController::InvalidAuthenticityToken exception notifications started flooding in.

Looking through the Rails docs and the mailing lists for the exception revealed little. I was setting my secret key for protect_from_forgery, and all of my forms used form_for which already sets the authentication token in the form.

It turns out that I had committed a simple, fatal error: resetting the session without redirecting.

When you reset the session, the session key changes. Redirecting after this will clear the user's session token, and a new one will be generated for the new session.

If you do what I did, however, the session gets reset, but the token will not. The next time your user submits any form (or POST link) your app will go batshit.

So the lesson: ALWAYS REDIRECT AFTER RESETTING THE SESSION. You'll be happier for it.


Comments are disabled