简体   繁体   中英

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).

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM