ruby-on-railsrubyapiruby-on-rails-4authenticity-token

API/JSON: Can't verify CSRF token authenticity


I'm trying to build a JSON API for my Rails application, and have written the following method:

  def create
    organization = Organization.find(params[:organization][:node_id])
    node = organization.nodes.build(nodes_params.except[:id])
    if node.save
      render json: node, status: :ok
    else
      render json: node, status: :bad_request
    end
  end

Trying the method in Postman returns the error: "Can't verify CSRF token authenticity". Based on this post I added the code below to the base controller. Unfortunately this made no difference. Does anyone understand the cause of the error?

protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?
private
  def json_request?
    request.format.json?
  end

Solution

  • As per comment on application_controller.rb you need to put this line protect_from_forgery with: :null_session.

    It will better if you make one more root controller for only all API's controller which is inherited from ApplicationController. i.e

    class Api::ApiController < ApplicationController
      #TODO
      protect_from_forgery with: :null_session
    end
    

    Other API's controllers

    class Api::V1::AddressesController < Api::ApiController
      #TODO
    end
    

    This controller class can help you to make changes only for API's root rather than whole application. You can also use this controller to make D.R.Y actions between various versions of API's.