jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery – 使用Spring CSRF和ajax Rest调用和带有Thymeleaf的HTML页面大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用带有CSRF的 Spring Security,我的javascript中有一些POST调用问题.对于我的页面,我使用Thymeleaf和HTML 5,对于我的控制器的Rest调用我使用jQuery.ajax.
如果我对我的表单使用ajax调用,如下所示:

$(function() {
    $("#saveCarButton").click(
            function() {
                var form = $("#addCarForm");        
                $.ajax({
                    type : "POST",url : form.attr("action"),data : form.serialize(),// all right with rest call
                    success : function(data) {...}  
                    //error during rest call
                    error : function(data) {
                        window.LOCATIOn.href = "/500";
                    }
                });
            });
});

一切正常,但当我打电话给这个函数时:

jQuery.ajax({
        url : 'upload',type: 'POST',contentType: false,processData: false,data:formData,beforeSend:function(xhr) {
            waiTingModal.showPleaseWait();
        },success: function(data,status,xhr){...}
        error: function(xhr,E){
        }
    }).complete(function() {
        //add timeout because otherwise user Could see a too fast waiTing modal
        setTimeout(function(){
            waiTingModal.hidePleaseWait();
        },1000);
    });

我收到错误403.
也许使用形式,使用thymeleaf,它工作正常,但第二种类型的请求我必须添加CSRF令牌.
我试过了

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

在我的html页面中我添加

!--  -->
<Meta name="_csrf" th:content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<Meta name="_csrf_header" th:content="${_csrf.headerNamE}"/>

为什么表格有效?
我使用表单时不需要添加任何内容
使用浏览器的开发工具可以看到_csrf和_csrf_header的危险吗?
谢谢

解决方法

这很可能是因为没有CSRF令牌通过403发送.

这是解决这些问题的方法(至少对我而言).

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);
}

总而言之,它将CSRF令牌附加到您通过ajax执行的任何发布请求.

大佬总结

以上是大佬教程为你收集整理的jquery – 使用Spring CSRF和ajax Rest调用和带有Thymeleaf的HTML页面全部内容,希望文章能够帮你解决jquery – 使用Spring CSRF和ajax Rest调用和带有Thymeleaf的HTML页面所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。