If you are using springboot , then the csrf token is automatically added to the response by the CsrfRequestDataValueProcessor . Springboot by default does not add the csrf token for GET but for POST it will be added as it modifies the state .To use token for instance with jsp :
<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}"
method="post">
<input type="submit"
value="Log out" />
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
when the form is loaded springboot will automatically inject the value for the csrf token through the post processor. If you want to use the csrf token in an ajax call then you will have to get the csrf token by inspecting the DOM and add it to your ajax request manually :
$(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);
});
});
Note : Both these examples are from the documentation itself.
Official doc.