使用spring secrity的时候ajax请求被拦截

背景是项目中使用Spring Security 进行安全控制

再使用Ajax的时候会报 403(ajax get  方式是没问题的 post 的时候会报)

Spring Security 原本是 防止 CSRF 攻击 现在 ajax 被误伤了...

然后下面贴解决方法,页面的head标签里 下记追加

(这里要说的是用的是thymeleaf模板 所有才会有 th:如果是jsp的话使用EL表达式吧th:去掉就能用了)

<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header"  th:content="${_csrf.headerName}"/>

然后用js取值

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

ajax中调用使用,其他和通常一样 beforeSend 里写下如下就可以了

 $.ajax({
            url : "",
            type : "POST",
            data : "",
            contentType : 'application/json;charset=utf-8',
            //async : false,
            beforeSend : function(xhr) {
                xhr.setRequestHeader(header, token);
            }, 
            success : function(resdata) {},
            error : function(xhr, ajaxOptions, throwError) { }
       });

转发自:https://www.cnblogs.com/zhufu9426/p/7814084.html

猜你喜欢

转载自blog.csdn.net/m0_38044453/article/details/81225069