0

can someone will explain to me this line of codes?

skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }

and should I use it? Why and why not. Thank you.

ana
  • 603
  • 6
  • 17
  • Also see http://stackoverflow.com/questions/23773730/rails-4-skipping-protect-from-forgery-for-api-actions –  Dec 04 '15 at 19:38

1 Answers1

1

The verify_authenticity_token is a before_action (a method called before every controller action, known as a before_filter prior to Rails 4) that Rails uses to protect from CSRF attacks. You can read more about how Rails does this here.

What this line of code is saying is: "if this is a JSON request then skip the CSRF check for this controller".

This is useful for JSON APIs which need to be made available to remote sites which are not on the same domain, and therefore would fail the CSRF check. This is safe, provided you make sure the API is being authenticated properly. However, if your controller is NOT going to be used by an external web application (and you are just doing AJAX stuff on your own site) then don't turn off the verify_authenticity_token check.

Community
  • 1
  • 1
rlarcombe
  • 2,958
  • 1
  • 17
  • 22
  • So, you're saying that there's no wrong with my code? On my console, the log says “WARNING: Can't verify CSRF token authenticity” for json devise requests. Is it dangerous? By the use, my controllers for API are seperate. I have also a rails admin on my web app. – ana Dec 02 '15 at 10:38
  • Have a read of this post: http://stackoverflow.com/questions/9362910/rails-warning-cant-verify-csrf-token-authenticity-for-json-devise-requests – rlarcombe Dec 02 '15 at 10:42
  • @rlarcombe would another way to state your authentication caveat re: remote servers be: "don't call these CSRF-unchecked endpoints from within your own Rails app"? –  Dec 04 '15 at 19:41
  • @ChrisCameron - Yes, I think so. – rlarcombe Dec 04 '15 at 19:46