Spring Security CSRF Token not working with AJAX

前端 未结 3 1005
南方客
南方客 2020-12-15 12:18

I have a problem in my spring boot app with the csrf token.

I have a form where I can edit a Person. A Person can have

Let us now imagine that the person has

相关标签:
3条回答
  • 2020-12-15 12:52

    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);
        }
    })
    
    0 讨论(0)
  • 2020-12-15 12:54
    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.

    0 讨论(0)
  • 2020-12-15 12:58

    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.

    0 讨论(0)
提交回复
热议问题