49

I am right now developing web APIs with Ruby on Rails. When the Rails app receives POST request without any csrf token, the following error message shall happen. Because the app has no views.

WARNING: Can't verify CSRF token authenticity

So my question is how can I escape csrf token check safely in this case?

Thank you very much in advance.

diveintohacking
  • 4,783
  • 6
  • 29
  • 43
  • 1
    My question was able to be solved by the past Q and A below. http://stackoverflow.com/questions/10167956/rails-shows-warning-cant-verify-csrf-token-authenticity-from-a-restkit-post – diveintohacking Feb 23 '13 at 13:46
  • This may help you! Take a look. https://stackoverflow.com/questions/35181340/rails-cant-verify-csrf-token-authenticity-when-making-a-post-request – Diogo Amaral Jun 23 '17 at 00:09

2 Answers2

66

You can do this by adding

skip_before_filter  :verify_authenticity_token

to your controller. This way all incoming requests to the controller skips the :verify_authenticity_token filter.

Kush Kella
  • 1,203
  • 8
  • 9
  • 3
    Any drawbacks from this solution? Is it the default thing to do for APIs? In application_controller there's an API "hint": `# For APIs, you may want to use :null_session instead.` – Sebastialonso Aug 07 '14 at 16:24
  • 3
    Yes, if your application runs only in browser, removing this will allow for CROSS-SITE-REQUEST-FORGERY http://en.wikipedia.org/wiki/Cross-site_request_forgery – Kush Kella Aug 09 '14 at 19:30
  • 3
    And for JSON APIs that are tied to your Rails Views, I recommend you use CSRF protection. But for APIs that are consumed by mobile clients or some other application separate from Rails app, this should be turned off. – Kush Kella Aug 09 '14 at 19:35
  • 1
    And lastly the `protect_from_forgery with: :null_session` essentially says that when an unverified request comes in, it should not reset the session completely. So for the next verified request, the session will be present. There are various options for handling unverified requests. http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html – Kush Kella Aug 09 '14 at 19:37
  • My app is being access only through JSON from my mobile clients. So no browser, no html views. I think I understand now, thanks! – Sebastialonso Aug 09 '14 at 21:34
20

For rails 4 it should be

skip_before_action :verify_authenticity_token, only: [:one_or_two_actions_here]

Note that you should avoid skipping verify_authenticity_token on all actions of your controller, instead use the option only to skip only where you have to. See the docs

Bryan Dimas
  • 1,389
  • 13
  • 18