【问题标题】:API/JSON: Can't verify CSRF token authenticityAPI/JSON:无法验证 CSRF 令牌的真实性
【发布时间】:2016-04-23 10:27:32
【问题描述】:

我正在尝试为我的 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

【问题讨论】:

  • 你使用哪个 Rails 环境来测试你的控制器的方法?
  • 我正在使用开发环境(使用 Cloud9 IDE)。现在正试图弄清楚@MaxWilliams 建议的帖子。
  • 如果您只想使用 json 请求测试组织创建,请尝试在测试环境中启动 rails。
  • 谢谢,我可以使用 protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json' }

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


【解决方案1】:

根据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 操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-15
    • 2015-07-24
    • 2014-06-16
    • 2017-05-26
    • 2012-05-08
    • 2015-12-29
    • 2023-03-26
    • 2016-09-17
    相关资源
    最近更新 更多