【问题标题】:Trying to use React/Ajax calls with Spring MVC and Thymeleaf尝试通过 Spring MVC 和 Thymeleaf 使用 React/Ajax 调用
【发布时间】:2016-03-23 08:58:19
【问题描述】:

根据文档,我应该能够在标头中包含 CSRF 令牌,使用 jquery 获取它们,并将它们包含在我的 ajax 调用的标头中。

不幸的是,包括

<html class='default' xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset='UTF-8'/>
    <meta http-equiv='X-UA-Compatible' content='IE=Edge,chrome=1' />
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
...
</html>

输出:

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="_csrf" content="${_csrf.token}">
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}">

而不是实际的令牌,所以没有什么可以抓住的。

有人用这种处理 ajax post/puts/deletes 的方式成功了吗?

参考: http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html

【问题讨论】:

标签: javascript spring spring-mvc csrf thymeleaf


【解决方案1】:

你忘记了前缀“th”。您的模板应如下所示:

<meta id="_csrf" name="_csrf" th:content="${_csrf.token}"/>
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>

还有你的 ajax 调用:

var token = $('#_csrf').attr('content');
var header = $('#_csrf_header').attr('content');

$.ajax({
    type: "POST",
    url: url,
    beforeSend: function (xhr) {
        xhr.setRequestHeader(header, token);
    },
    success: function (data, textStatus, jqXHR) {
        alert(status);
    },
    error: function (request, status, error) {
        alert(status);
    }
});

【讨论】:

  • 那行得通,如果他们在文档中有这个就好了。我忘记了索引在根目录,所以 react 不会抱怨命名空间!
  • 你救了我的命!百万感谢
【解决方案2】:

这是我的 ajax csrf 操作。

$(function() {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content"); 

$(document).ajaxSend(function (e, xhr, options) {
xhr.setRequestHeader(header, token);
}
}

我还使用 ajaxForm 插件提交表单,在这种情况下,我将 csrf 嵌入到操作 url 中。

希望对你有用。

【讨论】:

  • _csrf 令牌没有通过。
猜你喜欢
  • 2015-11-25
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 2014-01-25
  • 2014-11-20
  • 1970-01-01
相关资源
最近更新 更多