WARNING: Can't verify CSRF token authenticity in case of API development
Asked Answered
B

2

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.

Briefcase answered 23/2, 2013 at 13:18 Comment(2)
My question was able to be solved by the past Q and A below. #10168456Briefcase
This may help you! Take a look. #35181840Gelman
N
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.

Noisy answered 23/2, 2013 at 14:21 Comment(5)
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.Connatural
Yes, if your application runs only in browser, removing this will allow for CROSS-SITE-REQUEST-FORGERY en.wikipedia.org/wiki/Cross-site_request_forgeryNoisy
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.Noisy
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. api.rubyonrails.org/classes/ActionController/…Noisy
My app is being access only through JSON from my mobile clients. So no browser, no html views. I think I understand now, thanks!Connatural
D
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

Discordance answered 15/12, 2015 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.