Marek Michalik Marek Michalik - 3 months ago 101
Ruby Question

Devise token auth can't verify CSRF token authenticity

I try to create app in rails, which would be regular web application and also an api for mobile application written in react native. I take advantage of "devise token auth" gem along wiht "devise".
I added gems to Gemfile and ran bundle. Next I ran

rails g devise_token_auth:install User auth
. Finally I changed routes:

Rails.application.routes.draw do
devise_for :users

namespace :api do
scope :v1 do
mount_devise_token_auth_for 'User', at: 'auth'
end
end
end


Fortunately regular sign_in and sign_up work for web app, however when I try to send request to api using curl:

curl -H "Content-Type: application/json" -X POST -d '{"email":"test123@gmail.com","password":"aaaaaaaa"}' http://localhost:3000/api/v1/auth/sign_in


I get message "can't verify CSRF token authenticity"

Answer

The CSRF token authenticity check is originating from your Rails Application Controller.

# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception

There are a variety of ways you can handle the situation, but from the rails guide, they suggest adding a header:

By default, Rails includes jQuery and an unobtrusive scripting adapter for jQuery, which adds a header called X-CSRF-Token on every non-GET Ajax call made by jQuery with the security token. Without this header, non-GET Ajax requests won't be accepted by Rails. When using another library to make Ajax calls, it is necessary to add the security token as a default header for Ajax calls in your library. To get the token, have a look at tag printed by <%= csrf_meta_tags %> in your application view.