尝试将React/Ajax调用与SpringMVC和Thymelaf一起使用

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

本文关键字:SpringMVC Thymelaf 一起 调用 React Ajax      更新时间:2023-09-26

根据文档,我应该能够在头中包含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/delete吗?

参考: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中。

希望对你有用。