【问题标题】:Rails Can't verify CSRF token authenticityRails 无法验证 CSRF 令牌的真实性
【发布时间】:2017-07-15 04:03:40
【问题描述】:

我已经通过使用这样的 post 方法 api 成功创建了新记录(使用 Curl::PostField

curl_post_fields = [
    Curl::PostField.content('first_name', first_name),
    Curl::PostField.content('last_name', last_name),]

  contact = Curl::Easy.http_post("#{ENV['API_V1_URL']}/contacts", *curl_post_fields)
  contact.ssl_verify_peer = false
  contact.http_auth_types = :basic
  contact.username = ENV['API_V1_USERNAME']
  contact.password = ENV['API_V1_PASSWORD']
  contact.perform
  response = JSON.parse(contact.body_str)

但是当我通过像这样的补丁更新记录时(使用 json 请求参数):

contact = Curl.patch("#{ENV['API_V1_URL']}/contacts/#{qontak_id}",{:email => email, :gender_id => 8})
contact.ssl_verify_peer = false
contact.http_auth_types = :basic
contact.username = ENV['API_V1_USERNAME']
contact.password = ENV['API_V1_PASSWORD']
contact.perform
response = JSON.parse(contact.body_str)

我从服务器收到一些错误

Can't verify CSRF token authenticity

Filter chain halted as :authenticate rendered or redirected

我也关闭了 csrf protect_from_forgery with: :null_session

使用Curl::PostField 可能会自动包含csrf token,或者在patch or put method 中是否有类似Curl::Postfield 的方法?

【问题讨论】:

  • 嗨,伙计们,我仍然坚持这一点,有什么帮助吗?

标签: ruby-on-rails curl csrf csrf-protection curb


【解决方案1】:

您可以尝试显式跳过令牌过滤器。

在您的 API 控制器中:

skip_before_filter :verify_authenticity_token, only: [:put] respond_to :json

确保也重新启动您的服务器。希望这会有所帮助!

【讨论】:

  • 这会降低 API 的安全性吗?
  • 我想知道是否有另一种方法不关闭 csrf 或跳过令牌验证?
  • 您可以添加自己的 api_key 并在应用程序控制器中要求它。这是我前几天遇到的一个常见问题,我认为它与 Rails 5 有关。您正在运行仅 API 的应用程序吗?
  • 太不安全的解决方案
猜你喜欢
  • 2015-07-24
  • 2014-06-16
  • 2012-05-08
  • 2015-12-29
  • 2023-03-26
  • 2016-09-17
  • 2012-12-11
  • 2019-07-15
  • 2014-07-04
相关资源
最近更新 更多