【问题标题】:JSON request to Rails backend issue?对 Rails 后端问题的 JSON 请求?
【发布时间】:2015-04-17 12:41:43
【问题描述】:

所以在ApplicationController 类中调用protect_from_forgery with: :null_session

Admin 类继承 ApplicationController

关于为什么在映射到 Admin::LandingPagePhotosController#update 的请求后可能会抛出 Can't verify CSRF token authenticity 的想法?

Started PATCH "/admin/landing_page_photos/2" for 127.0.0.1 at 2015-02-16 16:44:29 -0500
  User Load (3.0ms)  SELECT  "users".* FROM "users"  WHERE ("users"."status" != 'deleted') AND "users"."id" = 2  ORDER BY "users"."id" ASC LIMIT 1
Processing by Admin::LandingPagePhotosController#update as JSON
  Parameters: {"landing_page_photo"=>{"position"=>"1"}, "id"=>"2"}
Can't verify CSRF token authenticity
   (0.7ms)  BEGIN
   (0.6ms)  COMMIT
Completed 401 Unauthorized in 26ms

【问题讨论】:

    标签: ruby-on-rails ruby csrf


    【解决方案1】:

    我不熟悉我明白你说的protect_from_forgery with: null_session是什么意思

    但您需要传递 CSRF 令牌,因为它不会通过 ajax 请求自动发送,除非您正在序列化使用 rails 创建的表单。

    查看此 SO 以获得简单的解决方案:

    Rails Ajax Can't verify CSRF token Authenticity

    【讨论】:

      【解决方案2】:

      通常,对于 JSON API,您可以不使用 CSRF 保护。

      这就是我实现它的方式:

      skip_before_filter :verify_authenticity_token,
                           if: Proc.new { |c| c.request.format == 'application/json' }
      

      我会将它放在您的 JSON API 控制器继承自的任何控制器中。我有一个我使用的 ApiController。

      最后,不要忘记以.json 结束您的请求,例如:example.com/api/v1/posts.json

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-18
        • 1970-01-01
        • 2012-02-18
        • 2020-06-11
        • 1970-01-01
        • 2014-01-13
        • 1970-01-01
        相关资源
        最近更新 更多