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

Share:
54,145
diveintohacking
Author by

diveintohacking

I am a Full-Stack software programmer teaching on Udemy.

Updated on July 09, 2022

Comments

  • diveintohacking
    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
    Sebastialonso almost 10 years
    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.
  • Kush Kella
    Kush Kella almost 10 years
    Yes, 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
    Kush Kella almost 10 years
    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
    Kush Kella almost 10 years
    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/…
  • Sebastialonso
    Sebastialonso almost 10 years
    My app is being access only through JSON from my mobile clients. So no browser, no html views. I think I understand now, thanks!