devise user sign_in gives authentication error for CSRF token authenticity token devise user sign_in gives authentication error for CSRF token authenticity token ruby-on-rails ruby-on-rails

devise user sign_in gives authentication error for CSRF token authenticity token


When the CSRF token is not correct, Rails will not read or do any updates to the session. It will still do any other actions the controller specifies, which explains why you see the DB update but don't end up logged in.

I notice that the authenticity_token in your log and in your page do not match. I realize this just may be because you captured a different request, but you should check that the one on the page matches the one in the log for the same request. I'm also assuming that you are using the proper tag in your view which generates a different authenticity_token each time, and are not just hard-coding the HTML input.

Do you see the same issue with forms unrelated to devise? If not, as a workaround, you can exempt your action from the CSRF check with the following code in your controller:

protect_from_forgery except: :sign_in

The odds of a CSRF attack against your sign in action seems pretty remote (<-pun) to me.

Also, if it's just with devise, then I'd suggest you file an issue with them, which you've already done.


Add this on the Application Controller (this works on Rails 5)

protect_from_forgery unless: -> { request.format.json? }

Add this to the Devise SessionController

skip_before_action :verify_authenticity_token, only: [:create]

Try it with curl

curl -X POST -v -H 'Content-Type: application/json' http://0.0.0.0:3000/users/sign_in -d '{"user" : {"email": "name@mail.com", "password": "secret" }}'


There was no problem with devise gem . I removed 'rails-api' gem and my app started working.