API / JSON:无法验证CSRF令牌的真实性

时间:2016-01-18 09:43:35

标签: ruby-on-rails ruby api ruby-on-rails-4 authenticity-token

我正在尝试为我的Rails应用程序构建JSON API,并编写了以下方法:

  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

在Postman中尝试该方法会返回错误:"无法验证CSRF令牌的真实性"。基于this post我将下面的代码添加到基本控制器。不幸的是,这没有任何区别有没有人理解错误的原因?

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

1 个答案:

答案 0 :(得分:4)

根据对application_controller.rb的评论,您需要放置此行 protect_from_forgery with: :null_session

如果为仅从ApplicationController继承的所有API控制器再创建一个根控制器,那将会更好。即

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

其他API的控制器

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

此控制器类可以帮助您仅对API的根而不是整个应用程序进行更改。您还可以使用此控制器在各种版本的API之间进行D.R.Y操作。