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

Cam*_*mel 47 javascript ruby-on-rails csrf backbone.js ruby-on-rails-3

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

luc*_*usa 65

最好的办法我在表格中解决了这个问题:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Run Code Online (Sandbox Code Playgroud)


Tho*_*uah 32

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

请参阅http://eunikorn.blogspot.com/2011/07/working-with-backbonejs-in-harmony-with.html,了解如何在每个骨干网请求中入侵csrf支持

  • 具体来说:`$.ajax(data: {authenticity_token: $('meta[name="csrf-token"]').attr("content")})` (2认同)

Jam*_*ard 7

我在 Rails 6 应用程序的 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>
Run Code Online (Sandbox Code Playgroud)

其呈现为:

<div id="app">
  <form action="/submit" method="post">
    <input type="hidden" name="authenticity_token" value="zl9PJiE...">
    ...
  </form>
</div>
Run Code Online (Sandbox Code Playgroud)