Reputation: 79
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":"[email protected]","password":"aaaaaaaa"}' http://localhost:3000/api/v1/auth/sign_in
I get message "can't verify CSRF token authenticity"
Upvotes: 2
Views: 4027
Reputation: 5855
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.
Upvotes: 2
Reputation: 156
This is actually considered a feature of Rails to protect you from CSRF attacks. Devise probably implements some form of forgery protection so you can't make non-GET requests without a proper token (this token is added to requests made from Rails itself but not Curl). You can look at the rails documentation for "protect_from_forgery". I would include a link but I am not sure which version of Rails you are using.
Upvotes: 0