Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails CSRF token authenticity and Devise

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 :)

like image 205
Abid Avatar asked Jul 31 '12 09:07

Abid


1 Answers

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

like image 193
Alex Shkolnikov Avatar answered Oct 24 '22 02:10

Alex Shkolnikov