Why I Cannot Do Ajax POST After Logged In (Spring Boot Default Login) - Save My Knowledge
Wednesday, January 14, 2015

Why I Cannot Do Ajax POST After Logged In (Spring Boot Default Login)

I have a page that save the data using ajax. And after I implement login function (login function that from spring boot, I cannot do save the data using ajax with error "error 405 method POST not allowed"). After I search on internet, this error occur because of CSRF is not right for the link that ajax target.

I tried many things start from disable CSRF attack, it work, but I didn't think this is become a good solution.
Then I search on internet and I found that I have to put the token on header and send it with the ajax.

Steps:
    Put this code on <head></head>
<meta th:if="${#httpServletRequest.remoteUser != null}" name="_csrf" th:content="${_csrf.token}" />
<!-- default header name is X-CSRF-TOKEN -->
<meta th:if="${#httpServletRequest.remoteUser != null}" name="_csrf_header" th:content="${_csrf.headerName}" />
    Put this javascript code
$(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);
    });
});

And then your ajax is ready to use