Ajax POST results in a 405 (Method Not Allowed) - Spring MVC

柔情痞子 提交于 2019-11-30 21:01:03

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.

In my case, with same problem, helps this:

  • add taglib:
 <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
  • add in jsp body:
<sec:csrfMetaTags />
  • add in ajax
headers: {"X-CSRF-TOKEN": $("meta[name='_csrf']").attr("content")}

P.S. Thanks to Illya Shulgin, cool ansver, now it here.

$.ajaxSetup({
    dataType: "json",
    beforeSend: function(xhr, settings){
        var csrftoken = $.cookie('CSRF-TOKEN');
        xhr.setRequestHeader("X-CSRF-TOKEN", csrftoken);
    },
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!