Search code examples
rubypostruby-on-rails-4csrfcsrf-protection

How to let external API send POST without turning protect_from_forgery off?


I'm using Rails 4.1.0.

I am in a project were my options are very limited. I need to have a form submit data to an external API. I stored the values of the form in the session because this application is multi-form based.

The problem is that when the API POSTs back to my Rails application, the session is nullified.

I know this happens because protect_from_forgery in my app/controllers/application_controller.rb

How can I keep the session just a little longer, until the API POSTs back to my confirmation page (saying the form was submitted successfully)?


Solution

  • You can turn off request forgery protection for just a single action:

    skip_before_action :verify_authenticity_token, only: :my_action_name
    

    Replace :my_action_name with the name of the action the API POSTs back to.

    Source: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html#method-i-protect_from_forgery