I\'m trying to make an ajax call to my Spring controller/action with POST method, and return an object from the server with @ResponseBody. The strange situation is that it s
$.ajaxSetup({
dataType: "json",
beforeSend: function(xhr, settings){
var csrftoken = $.cookie('CSRF-TOKEN');
xhr.setRequestHeader("X-CSRF-TOKEN", csrftoken);
},
});
In my case, with same problem, helps this:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:csrfMetaTags />
headers: {"X-CSRF-TOKEN": $("meta[name='_csrf']").attr("content")}
P.S. Thanks to Illya Shulgin, cool ansver, now it here.
After many hours of research and tests, I finally got it, ant it was a (very very) stupid situation. So, in my question I said
so I disabled it (csrf on spring-security.xml) and still have the issue.
No, I didn't disabled it. I was trying to disable it doing
<!--
<csrf/>
-->
But I should be doing:
<csrf disabled="true"/>
Commenting csrf tag does NOT disable csrf, this is because csrf is enabled by default! After find the problem is really easy to say that is a stupid mistake, but as I added csrf tag to enable it, I thought that commenting it would disable it. Find the answer on Spring Documentation
Now, back into my problem. To fix the 405 error message in a POST AJAX call WITH CSRF ENABLED, it was really easy. I keep the csrf parameters in JS variables like this:
<script type="text/javascript">
var csrfParameter = '${_csrf.parameterName}';
var csrfToken = '${_csrf.token}';
</script>
and then my ajax call looks like this:
var jsonParams = {};
jsonParams['parentId'] = 1;
jsonParams[csrfParameter] = csrfToken;
$.ajax({
type: 'POST',
cache: false,
url: /admin/events/loadEvents,
data: jsonParams,
dataType = 'json',
contentType = 'application/json',
...
});
Working like a charme. Hope that helps someone in the future.