Rails自动更新CSRF令牌以重复JSON请求

问题描述 投票:1回答:1

我有一个包含大量远程表单的单页ROR应用。我的问题是,在非幂等请求之后,Rails更改了CSRF令牌,并使嵌入在页面元中的令牌无效。因此,如果不刷新页面,则重复的非虚假请求将失败。

例如,通过POST提交的远程表单因验证错误而失败,并且重新提交表单时,其InvalidAuthenticityToken错误导致失败。

我认为默认情况下该问题足以使Rails处理,但显然不是。

jquery ruby-on-rails json security csrf
1个回答
5
投票

我对此的解决方案,这里有什么陷阱吗?:

application_controller.rb:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  # callback to set CSRF TOKEN for non-idempotent Ajax request
  after_action :add_csrf_token_to_json_request_header

  private

  def add_csrf_token_to_json_request_header
    if request.xhr? && !request.get? && protect_against_forgery?
      response.headers['X-CSRF-Token'] = form_authenticity_token
    end
  end
end

application.js:

//= require jquery2
//= require jquery_ujs
//= require turbolinks=

$( document ).ajaxComplete(function( event, xhr, settings ) {
  header_token = xhr.getResponseHeader('X-CSRF-Token');
  if (header_token) $('meta[name=csrf-token]').attr('content', header_token)
});
© www.soinside.com 2019 - 2024. All rights reserved.