Last Updated: February 25, 2016
·
38.91K
· dpaluy

Rails 4 solution for "Can't verify CSRF token authenticity” json requests

Instead of complete turning off CSRF, you can do the following in Rails 4:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
end

5 Responses
Add your response

Unfortunately, the above matches exactly. I changed your suggestion to:

class ApplicationController < ActionController::Base
    protect_from_forgery with: :null_session,
      if: Proc.new { |c| c.request.format =~ %r{application/json} }
end

Now it handles additional content types terms such as:

application/json; charset=utf-8

Thanks for your idea above, it got me past my problem.

over 1 year ago ·

You don't have to match manually, there is an easier way:

protectfromforgery with: :null_session, if: Proc.new { |c| c.request.format.json? }</code></pre>
over 1 year ago ·

Using rails 4.1.5, if: doesn't work, I had to

protect_from_forgery with: :null_session, only: Proc.new { |c| c.request.format.json? }
over 1 year ago ·

I am using Rails 4.2.5
My authentication is home made based on M. Hartl tutorial.
Everything worked well until yesterday.
Today, after a bundle update I cannot get a session for user logging in.
The error in the Puma server log is: "Can't verify CSRF token authenticity"
I attempted all the suggestions above but none is working in my case.
Any help to overcome this will be much appreciated.

over 1 year ago ·

¡Excelente!, muchas gracias David Paluy y a los usuarios que fueron mejorando el código.

over 1 year ago ·