Ad

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

Ad

Answer

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);
    }
});
Ad
source: stackoverflow.com
Ad