Spring Security CSRF Token not working with AJAX

邮差的信 提交于 2019-11-29 02:24:31
Manu Zi

OK, after strugglin with all that, I get the following result.

I added the fail method to the Ajax construct and get the following message:

"Failed to execute 'setRequestHeader' on 'XMLHttpRequest': '${_csrf.headerName}' is not a valid HTTP header field name."

the official spring site advises that you have to put this: <sec:csrfMetaTags /> or from other sources, this: <meta name="_csrf" th:content="${_csrf.token}"/> in your html file.

After this, you should be able to access these attributes in your JavaScript, but in my case I get undefined and ${_csrf.headerName}.

A last try was to take the value from the hidden value (chapter 24.5: http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#the-csrfmetatags-tag).

Now, I have the following:

$(function () {
    var token = $("input[name='_csrf']").val();
    var header = "X-CSRF-TOKEN";
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});

$.ajax({
    url: "./delete/car",
    type: "POST",
    success:function(response) {
        alert(response);
    }
});

With this it works like a charm.

Another way, you can use the following code:

$.ajax({
    url : './delete/car',
    headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()},
    type : 'POST',
    success : function(result) {
        alert(result.msgDetail);
    }
})
  1. I suggest you first check if a valid csrf token and the header have been generated using chrome debugger. If not, then have you added the <sec:csrfMetaTags /> in the <head>?(you will need to import the spring security taglibs). If using Apache tiles, you will have to add this at the <head> section of the template file being used for the view.

  2. If the token is not empty, then in your security-context/configuration file, check if you have disabled csrf security by any chance. By default it is enabled and needs to be for this process to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!