How to turn off rails protect_from_forgery filter only for json

♀尐吖头ヾ 提交于 2019-12-01 19:02:41
dombesz

Take a look at this post: http://zadasnotes.blogspot.com/2010/11/rails-3-forgery-csrf-protection-for.html [archive.org]

Update

The article has been removed since then, so I did a quick search and I found the original author of the article posting this question on SO.

Rails 3 AJAX request authenticity token ignored

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
Sasha B.

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

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

protect_from_forgery unless: -> { request.format.json? }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!