【问题标题】:Rails CSRF issue on receiving POST request from API从 API 接收 POST 请求时出现 Rails CSRF 问题
【发布时间】:2016-06-15 17:58:10
【问题描述】:

我正在开发与 API 交互的 Rails 应用程序。现在有一个步骤,API 会将 POST 请求发送到应用程序,我尝试将返回的数据保存到数据库中。但看起来应用程序不接受数据并返回 422 : Unprocessable Entity

这是来自日志文件的错误消息

W, [2016-02-29T12:21:54.865291 #22727]  WARN -- : Can't verify CSRF token authenticity
I, [2016-02-29T12:21:54.865839 #22727]  INFO -- : Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
F, [2016-02-29T12:21:54.870852 #22727] FATAL -- :
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
 actionpack (4.2.4) lib/action_controller/metal/request_forgery_protection.rb:181:in `handle_unverified_request'
actionpack (4.2.4) lib/action_controller/metal/request_forgery_protection.rb:209:in `handle_unverified_request'
actionpack (4.2.4) lib/action_controller/metal/request_forgery_protection.rb:204:in `verify_authenticity_token'

我也试过禁用 CSRF

class MyController < ApplicationController

    skip_before_action :verify_authenticity_token

end

但还是不行。

请帮我解决这个问题。我已经为这个问题苦苦挣扎了三天。

【问题讨论】:

  • protect_from_forgery with: :null_session

标签: ruby-on-rails csrf


【解决方案1】:

你可以试试这个

    protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 2021-09-06
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多