如何在javascript中创建的表单中添加CSRF保护

Rails - How to add CSRF Protection to forms created in javascript?

本文关键字:表单 添加 CSRF 保护 创建 javascript      更新时间:2023-09-26

我正在使用backbone.js,它工作得很好。但是我作为javascript模板创建的表单缺少rails csrf保护令牌。我如何将它添加到我在javascript中创建的模板?

我解决这个问题的最好方法,在表单中:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
更新:

看起来form_authenticity_token在较新的rails版本中是私有的。

如果是这样的话,我的建议是:在控制器中声明一个变量,如下所示:@form_token = form_authenticity_token在你想要的视图中使用

如果你的布局中有<%= csrf_meta_tag %>并且可以从js中访问,那么你可以使用$('meta[name="csrf-token"]')

关于如何在每个主干请求中插入csrf支持的想法请参阅http://eunikorn.blogspot.com/2011/07/working-with-backbonejs-in-harmony-with.html

我在Rails 6应用程序的Vue组件中有一个表单。

令我惊讶的是,在Vue模板中包含一个名称为authenticity_token的隐藏输入就足够了,并且在页面加载时,Rails用CSRF保护令牌填充了该值。

<template>
  <div id="app">
    <form
      action="/submit"
      method="post"
      @submit.prevent="onSubmit"
    >
      <input
        type="hidden"
        name="authenticity_token"
        value=""
      >
      <!-- rest of form -->
    </form>
  </div>
</template>

呈现为:

<div id="app">
  <form action="/submit" method="post">
    <input type="hidden" name="authenticity_token" value="zl9PJiE...">
    ...
  </form>
</div>

您可以在每个使用'post'或'delete'的表单前添加csrf令牌。下面是coffeescript:

$ -> 
  for f in $("form")
    if f.method == 'post' or f.method == 'delete'
      $(f).prepend("<input type='hidden' name='authenticity_token' value='" + token + "'>")

确保您的布局中有<%= csrf_meta_tags %>。它应该已经在标准的"application"布局中,但是如果你使用不同的布局,请添加它。

对于Rails 4.2.2,你不允许使用

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

从你的.js.erb资产文件

然而,您可以在.js.erb文件中创建表单,并在包含表单.html.erb文件的视图中使用hidden_field_tag helper来生成令牌元素。由于此元素将在表单外部生成,您可以使用jquery将此元素附加到表单中。

研究案例:SweetAlert(第一个版本,版本似乎也解决了这个问题)

<标题> show.js.erb h1> show.html.erb h1> /html>