简体   繁体   中英

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

according to the docs, I should be able to include the CSRF tokens in the header, grab them with jquery, and include them in the headers of my ajax calls.

Unfortunately, including

<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>

outputs:

<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}">

And not the actual token so there is nothing to grab.

Has anyone had success with this way of handling ajax post/puts/deletes?

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

You forget the prefix "th". your template should look like this:

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

and your ajax call:

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);
    }
});

Here is how I did my 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);
}
}

I also use ajaxForm plugin to submit forms, in which case i embed the csrf into the action url.

Hope that works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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