8z7z3a
Last Updated: February 25, 2016
·
30.43K
· dpaluy
3129de6b479cc965513311f1ddcc268a

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
Say Thanks
Respond

5 Responses
Add your response

16087
A4bfe405fb5d520e12ca94a1e8ee4654

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 ·
16391
5f2953d0a7e0a5a4fcb46cf0fcb769ad

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 ·
18136
None

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 ·
24662
None

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 ·
26548
None

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

over 1 year ago ·