Spring Security CSRF Token not working with AJAX call & form submit in same JSP

后端 未结 3 901

I am trying to implement spring security (ver 3.2.3) CSRF token in my project by referring below links

http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-

3条回答
  •  悲&欢浪女
    2021-01-06 08:38

    To make an AJAX/JSON request with CSRF enabled you have to pass CSRF token as a HTTP Request Header, not a parameter or other data.

    On the page, your meta tags should look like these:

    
    
    

    Then, prepare values somewhere in the JS code:

    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    

    Pass the CSRF token as a header:

    $.ajax({
            type: "GET",
            async: false,
            url: './getMerchantByInstitution.htm',
            data: "institutionId=" + option,
            beforeSend: function(xhr) {
                // here it is
                xhr.setRequestHeader(header, token);
            },
            success: function(obj) {
                //  ....
            },
            ....
    

    Though it's totally up to you, I'd recommend to use something like JSON.stringify to pass the data, but it depends, of course.

    The reference is here:

    http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html#csrf-include-csrf-token-ajax

    Hope this helps.

提交回复
热议问题