How to turn off rails protect_from_forgery filter only for json
Asked Answered
R

3

10

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_from_forgery filter. Because the client will not retrieve any data from the server, there is no way that the client can receive auth_token so I would like to turn off the protect_from_forgery option only for json requests (I thought rails3 does this in default but apparently it does not).

I know similar topic is discussed at here but in that case, he receives auth_token before sending post request.

So my question is turning off the protect_from_forgery only for json is good way of doing this? If yes, how to do so? If no, what is the alternative?

FYI, I use following ajax request

$.ajax({
             type: 'POST',  
             url: "http://www.example.com/login.json",  
             data: { 'email': emailVal, 'password': passwordVal },  
             success: onSuccess,  
             error: onError,  
             dataType: "json"  
});

and I get ActionController::InvalidAuthenticityToken error.

By the way, following curl command works though...

curl -H "Content-Type: application/json" -c cookies.txt -d '{"email": emailVal, "password": passwordVal}' -X POST http://www.example.com/login.json -i
Riplex answered 19/4, 2011 at 13:38 Comment(0)
W
18

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
Wei answered 28/3, 2014 at 14:8 Comment(2)
Note that this makes it vulnerable to csrf.Scale
Use skip_before_action on Rails 5+.Farsighted
F
7

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

protect_from_forgery unless: -> { request.format.json? }
Farsighted answered 18/7, 2018 at 23:24 Comment(0)
B
1

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

Belia answered 23/3, 2014 at 20:46 Comment(1)
this might not be possible, if the UI is being built in a different project entirelySharp

© 2022 - 2024 — McMap. All rights reserved.