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

according to the docs, I should be able to include CSRF tokens in the header, grab them using 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 a real token, so there is nothing to capture.

Has anyone had success in this way of handling ajax / puts / delete messages?

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

+1
source share
2 answers

You forgot 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);
                        }
                    });
+4

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

, .

+1

Source: https://habr.com/ru/post/1623954/


All Articles