ActionController InvalidAuthenticityToken in Api :: V1 :: UsersController # create

I am going to create a soothing API using Ruby on Rails. I want to create, delete, show and update data. All of them must be JSON in order to get it on Android devices. I also use Postman to test my APIs. This is what I did:

My controller:

class Api::V1::UsersController < ApplicationController respond_to :json def show respond_with User.find(params[:id]) end def create user=User.new(user_params) if user.save render json: user, status: 201 else render json: {errors: user.errors}, status: 422 end end def update user=User.find(params[:id]) if user.update(user_params) render json: user, status:200 else render json: {erros: user.errors},status: 422 end end def destroy user=User.find(params[:id]) user.destroy head 204 end private def user_params params.require(:user).permit(:email,:password,:password_confirmation) end end 

and this is my route file:

 Rails.application.routes.draw do devise_for :users namespace :api, defaults:{ format: :json } do namespace :v1 do resources :users, :only=>[:show,:create,:update,:destroy] end end end 

and also added the following code to my Gemfile:

 gem "devise" gem 'active_model_serializers' 

I do not know why, when I want to create through the postman, I get the following error:

 ActionController InvalidAuthenticityToken in Api::V1::UsersController#create 
+5
source share
2 answers

You need to make the following changes to application_controller.rb

Change

 class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end 

to

 class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :null_session end 

EDIT

It is best to skip authentication for a specific controller.

 class Api::V1::UsersController < ApplicationController skip_before_action :verify_authenticity_token respond_to :json # ... end 
+6
source

For web controllers :

 protect_from_forgery with: :exception 

For API controllers :

 protect_from_forgery with: :null_session 

You can also choose when to run this test using the prepend parameter (the default value for this option is false)

 protect_from_forgery with: :null_session, prepend: true 

As stated in the documentation

This is useful if you want fake protection to depend on other callbacks, such as authentication methods (Oauth vs Cookie auth)

0
source

Source: https://habr.com/ru/post/1262700/


All Articles