How to turn off rails protect_from_forgery filter only for json

后端 未结 3 580
一向
一向 2021-01-17 22:35

I have web site built with Rails3 and now I want to implement json API for mobile client access. However, sending json post request from the client because of the protect_fr

相关标签:
3条回答
  • 2021-01-17 23:27

    Instead of disabling the CSRF check you can pass the authenticity_token field in your forms, eg:

    <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
    

    http://apidock.com/rails/v2.0.0/ActionController/RequestForgeryProtection/ClassMethods/protect_from_forgery

    0 讨论(0)
  • 2021-01-17 23:29

    Add the code below to your ./app/controllers/application_controller.rb:

    protect_from_forgery unless: -> { request.format.json? }
    
    0 讨论(0)
  • 2021-01-17 23:35

    You can just skip the authenticity token check if its a json request

    class ApplicationController < ActionController::Base
      skip_before_filter :verify_authenticity_token, if: :json_request?
    
      def json_request?
        request.format.json?
      end
    end
    
    0 讨论(0)
提交回复
热议问题