8
votes

I am having issues with rails authenticity token and Devise login/logout.

I am using backbone js to build a single page app so I use ajax to login/logout the user. Here is what I am observing and I don't understand exactly why this is happening.

I have csrf_meta_tags in my layout. the page loads, I click a login button fill out a form and submit it, I am logged in successfully. I can do things a logged in user should be able to do.

Now I click a logout button which sends a DELETE request via ajax and I am successfully logged out.

All the process above is on a single page no page reloads happen its all ajax.

Now when I click login again and fill out the form it sends the ajax request, logs me in but shows a warning message at the server console.

WARNING: Can't verify CSRF token authenticity

Now why did it (devise) log me in, in the first place if it(rails) couldn't verify CSRF token authenticity.

and now when i try to do things that a logged in user should be able to do it fails, posting a form fails with error message from devise

401 Unauthorized {"error":"You need to sign in or sign up before continuing."}

and a warning on the server console

WARNING: Can't verify CSRF token authenticity

and at this point I am logged out, If I refresh the page myself I can see that I am no more logged in.

What is going on ?

Does my first authenticity token expire after I logged out the first time ?

I am using

rails (3.2.3)
devise (2.1.0)

Thanks in advance :)

1
Exactly the same problem I am having. Please comment if you have found the solution. Thxvrepsys
I know why the issue is arising. Its because csrf token expires on signout and since its a ajax based sign_out the page doesn't reload and the new token doesn't get on the page hence causing a mismatch on subsequent request. for now I am reloading the page on sign_out to work around the issue. Someone (may be you ?) posted the same on the devise mailing list. Lets see if we can get something there...Abid
@Abid, i got the same error with my old rails project, it make me crazy, did u find the solution? if u hava, let us know , tkxneocanable
@Abid same error on my application.Diego Dias
I don't know if this should be in an answer, if so let me know :), maybe this is your answer stackoverflow.com/questions/11845500/…Isaac Zepeda

1 Answers

1
votes

You have to send authenticity_token variable with all your ajax requests. You can fill it from page's meta tag.