How to turn off rails protect_from_forgery filter only for json How to turn off rails protect_from_forgery filter only for json ruby-on-rails ruby-on-rails

How to turn off rails protect_from_forgery filter only for json


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?  endend


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

protect_from_forgery unless: -> { request.format.json? }


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