protect_from_forgery и Незаметный JavaScript

Поскольку значение одно и то же, мы можем догадаться, что функция печати, обрабатывающая это значение, может быть незначительной разницей в этом: -)

13
задан Matt Grande 8 April 2009 в 19:41
поделиться

2 ответа

In your layout, add this before any other JS runs:

<script>
  function authToken() {
    return '<%= form_authenticity_token if protect_against_forgery? -%>';
  }
</script>

authToken is coded as a function so that it's less likely you'll accidentally overwrite it with other JavaScript.

Alternatively, as of Rails 3, the auth token is embedded as a tag, which you can read with:

<script>
  function authToken() {
    return $('meta[name="csrf-token"]').attr('content');
  }
</script>

In your main JS, you can then call authToken(), and it'll return your authenticity token as a string to include in your Ajax calls. For example, using jQuery:

$.ajax({
  type: 'PUT',
  url:  url,
  data: {
    foo: bar,
    authenticity_token: authToken()
  },
  complete: function(data) {}
});

Note that if you use Rails' built-in form_for helper, it automatically adds the authenticity token in a hidden input. If you want to send all of the form's data, including the hidden auth token, you can simply use:

var $form = $('form');
$.ajax({
  url:      $form.attr('action'),
  type:     $form.attr('method'),
              // "get" or "post"; overridden by Rails' hidden "_method"
              // input value, e.g., "put"
  data:     $form.serialize(),
              // Includes hidden "authenticity_token" and "_method" inputs
  complete: function(data) {}
});

This pattern is often useful when you've already written a form that works without JS, and you're adding an unobtrusive layer of JS that simply sends the form's data via Ajax.

21
ответ дан 1 December 2019 в 21:53
поделиться

Спасибо за указанное выше решение.
Я использую на своем сайте несколько стандартных форм, которые не используют rails form_tag, поэтому вместо этого я просто добавил его как скрытый элемент формы.

<form action="...">
    <%= hidden_field_tag 'authenticity_token', form_authenticity_token if protect_against_forgery? %>
    ... rest of form...
</form>

Прекрасно работает.

3
ответ дан 1 December 2019 в 21:53
поделиться
Другие вопросы по тегам:

Похожие вопросы: