Skip to content

Instantly share code, notes, and snippets.

@rbreve
Last active August 28, 2018 05:34
Show Gist options
  • Save rbreve/497b2f586c4edcf357cfddc4aaab2fcd to your computer and use it in GitHub Desktop.
Save rbreve/497b2f586c4edcf357cfddc4aaab2fcd to your computer and use it in GitHub Desktop.
JSON Devise Authentication avoid "Can't verify CSRF token authenticity" Rails 5.x

To be able to authenticate a user using JSON using Devise you need to bypass the CSRF token warning that Rails throws when signing in with JSON, this is useful when trying to use a mobile app that will consume your app api and authenticate. The documention to solve this problem is outdated on google or stack overflow. Rails 5 did some changes, this is how to do it.

Add this on the Application Controller

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

More info here

Add this to the Devise SessionController

skip_before_action :verify_authenticity_token, only: [:create]

This is how the json parameters should be formated

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" }}'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment