WARNING: Can't verify CSRF token authenticity in case of API development
54,145
Solution 1
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.
Solution 2
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
Author by
diveintohacking
I am a Full-Stack software programmer teaching on Udemy.
Updated on July 09, 2022Comments
-
diveintohacking almost 2 years
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.
-
Sebastialonso almost 10 yearsAny 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.
-
Kush Kella almost 10 yearsYes, if your application runs only in browser, removing this will allow for CROSS-SITE-REQUEST-FORGERY en.wikipedia.org/wiki/Cross-site_request_forgery
-
Kush Kella almost 10 yearsAnd 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 almost 10 yearsAnd 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/… -
Sebastialonso almost 10 yearsMy app is being access only through JSON from my mobile clients. So no browser, no html views. I think I understand now, thanks!