Rails - 如何向用 javascript 创建的表单添加 CSRF 保护?

发布于 2024-12-21 01:44:20 字数 100 浏览 2 评论 0原文

我正在使用backbone.js,它效果很好。但我作为 JavaScript 模板创建的表单缺少 Rails csrf 保护令牌。如何将其添加到我用 JavaScript 创建的模板中?

I'm using backbone.js and it works great. but the forms I'm creating as a javascript template lacks the rails csrf protection token. How do I add it to templates I'm creating in javascript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

相权↑美人 2024-12-28 01:44:20

我解决这个问题的最佳方法是在表单内:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

更新:

看起来 form_authenticity_token 对于较新的 Rails 版本中的控制器来说是私有的。

如果您是这种情况,我的建议是:在控制器中声明一个变量,如下所示:
@form_token = form_authenticity_token
并在您正在寻找的视图中使用它。

Best way I solved this, inside the form:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Update:

It looks like the form_authenticity_token is private for controllers in the newer rails versions.

If that's the case for you, what I suggest is: declare a variable in a controller like:
@form_token = form_authenticity_token
and use it in the view you are looking for.

酒废 2024-12-28 01:44:20

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

请参阅 http://eunikorn.blogspot.com/2011/07/working-with- backbonejs-in-harmony-with.html 了解如何将 csrf 支持融入到每个主干请求中

If you have <%= csrf_meta_tag %> in your layout somewhere and that is accessible to you from the js, then you can access it using $('meta[name="csrf-token"]')

See http://eunikorn.blogspot.com/2011/07/working-with-backbonejs-in-harmony-with.html for an idea on how to hack in csrf support into each backbone request

相对绾红妆 2024-12-28 01:44:20

我在 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>

I have a form inside a Vue component in a Rails 6 app.

To my surprise, it was sufficient to include a hidden input with the name authenticity_token within the Vue template and on page load, Rails filled out the value with a CSRF protection token.

E.g.

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

Which gets rendered as:

<div id="app">
  <form action="/submit" method="post">
    <input type="hidden" name="authenticity_token" value="zl9PJiE...">
    ...
  </form>
</div>
生活了然无味 2024-12-28 01:44:20

您可以将 csrf 令牌添加到使用“post”或“delete”的每个表单前面。这是在 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 %>;在你的布局中。它应该已经位于标准“应用程序”布局中,但如果您使用不同的布局,请添加它。

You can prepend the csrf token to every form that uses 'post' or 'delete'. Here it is in coffeescript:

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

Make sure you have <%= csrf_meta_tags %> in your layout. It should already be in the standard 'application' layout, but add it if you're using a different layout.

献世佛 2024-12-28 01:44:20

至于 Rails 4.2.2,您不能

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

.js.erb 资产文件中使用。

但是,您可以在 .js.erb 文件内创建表单,并在包含表单 .html.erb 文件的视图中使用 hidden_​​field_tag 帮助器生成令牌元素。由于此元素将在表单外部生成,因此您可以使用 jquery 将此元素附加到表单。

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

show.js.erb

$('.js-button-apply-offer').click(function(e) {
var urlOffer = $(this).attr('data-url-offer');
var modalParams = {
    type: 'warning',
    title: 'add file',
    text: '<p>Need to add a file before continuing</p>' // This is a hack for Sweet alert, solved in SweetAlert2 Consider upgrade
    +"<form action='"+urlOffer+"' id='formCustomCV' method='post' enctype='multipart/form-data' data-remote='true'>"
    + "<input type='file' name='custom_cv' id='fileToUploadAlert' accept='application/pdf'>\n"
    +"</form>",
    html: true,
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Send',
    cancelButtonText: 'Cancel',
    closeOnConfirm: false
  }
swal(modalParams,
function(){
  var form_token = $('#form_token');
  $('#formCustomCV').append(form_token).submit(); //update to submit using ajax
});

show.html.erb

<%= button_tag t('offers.offer.apply'),
  class: 'center-block btn btn-success js-button-apply-offer',
  id: "js-button-apply-offer",
  data: {
    url_offer: apply_talents_offer_path(@offer),
  } 
%>
<%= hidden_field_tag :authenticity_token, form_authenticity_token, id: :form_token %>

As for Rails 4.2.2 you are not allowed to use

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

from your .js.erb assets file.

However You can create the form inside the .js.erb file and in the view containing the form .html.erb file use the hidden_field_tag helper to generate the token element. As this element is going to be generated outside the form you can use jquery to append this element to the form.

Case of study: SweetAlert (first version, version too seems to have solved this problem)

show.js.erb

$('.js-button-apply-offer').click(function(e) {
var urlOffer = $(this).attr('data-url-offer');
var modalParams = {
    type: 'warning',
    title: 'add file',
    text: '<p>Need to add a file before continuing</p>' // This is a hack for Sweet alert, solved in SweetAlert2 Consider upgrade
    +"<form action='"+urlOffer+"' id='formCustomCV' method='post' enctype='multipart/form-data' data-remote='true'>"
    + "<input type='file' name='custom_cv' id='fileToUploadAlert' accept='application/pdf'>\n"
    +"</form>",
    html: true,
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Send',
    cancelButtonText: 'Cancel',
    closeOnConfirm: false
  }
swal(modalParams,
function(){
  var form_token = $('#form_token');
  $('#formCustomCV').append(form_token).submit(); //update to submit using ajax
});

show.html.erb

<%= button_tag t('offers.offer.apply'),
  class: 'center-block btn btn-success js-button-apply-offer',
  id: "js-button-apply-offer",
  data: {
    url_offer: apply_talents_offer_path(@offer),
  } 
%>
<%= hidden_field_tag :authenticity_token, form_authenticity_token, id: :form_token %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文