Search code examples
ruby-on-railsajaxruby-on-rails-4csrf

CSRF token with multiple forms


I have two forms on a single page, both of which are declared like this:

form_for @student, {remote:true, format: 'json'} do |f|

and

form_for @teacher, {remote:true, format: 'json'} do |f|

However, when I click the submit button for the teacher form, it errors out, saying "Invalid CRSF token" for that request. The requests for the student form work fine.

I've got <%= csrf_meta_tags %> in the main application.html.erb file, and the teacher form does have a CSRF token in the submit. I'm not doing an API, I just want the form to be handled via AJAX (I do some client-side error handling and confirmation).


Solution

  • You'll need to disable CSRF protection for json requests, according to the Rails docs: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html

    It's important to remember that XML or JSON requests are also affected and if you're building an API you'll need something like:

    class ApplicationController < ActionController::Base
      protect_from_forgery
      skip_before_action :verify_authenticity_token, if: :json_request?
    
      protected
    
      def json_request?
        request.format.json?
      end
    end
    

    See also: