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
Written by David Paluy
Related protips
5 Responses
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.
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>
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? }
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.
¡Excelente!, muchas gracias David Paluy y a los usuarios que fueron mejorando el código.