繁体   English   中英

尝试在Spring MVC和Thymeleaf中使用React / Ajax调用

[英]Trying to use React/Ajax calls with Spring MVC and Thymeleaf

根据文档,我应该能够将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发布/提交/删除成功吗?

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

您忘记了前缀“ 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);
    }
});

这是我做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中。

希望对您有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM