I am using Spring Security with CSRF and I have a problem with some POST call in my javascript. For my page I use Thymeleaf and HTML 5, to call Rest for my controller I use jQuery.ajax. If I use ajax call for my form as follows:
$(function() {
$("#saveCarButton").click(
function() {
var form = $("#addCarForm");
$.ajax({
type : "POST",
url : form.attr("action"),
data : form.serialize(),
success : function(data) {...}
error : function(data) {
window.location.href = "/500";
}
});
});
});
everything works fine, but when I call, for example, this function:
jQuery.ajax({
url : 'upload',
type: 'POST',
contentType: false,
processData: false,
data:formData,
beforeSend:function(xhr) {
waitingModal.showPleaseWait();
},
success: function(data,status,xhr){...}
error: function(xhr,status,e){
}
}).complete(function() {
setTimeout(function(){
waitingModal.hidePleaseWait();
}, 1000);
});
I get error 403. Maybe with the form using thymeleaf it works fine, but with the second type of request I have to add the CSRF token. I tried using
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
and on my html page I added
!-- -->
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
Why does this work with form? Do I need to add anything when I use the form? Is it dangerous that _csrf and _csrf_header are visible using the browser dev device? thanks