Spring Boot-Security-CSRF(POST 请求默认拦截)

在使用Spring Security时,SpringSecrity默认开启CSRF保护,所有的get请求都可以正常访问,但是post请求报错403

方式1:禁用CSRF保护

这种比较暴力,如果禁用可能就违背了SpringSecrity的安全认证了。


@Configuration
@Order
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //禁用csrf保护
        http.csrf().disable();
 
        http.authorizeRequests()
                .antMatchers("/hello", "/hellopost").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().and().httpBasic();
 
    }
}

方式2

<!--获取-->
<meta th:name="_csrf" th:content="${_csrf.token}"/>
<!-- 默认的header name是X-CSRF-TOKEN -->
<meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>
<!--发送ajax请求-->
function mdImageAjax(){
        //var submit = $("#ImageSubmit").submit();
        //alert(submit);

        //$("#uploadframe").val;

        //return ;
        var formData = new FormData($('#ImageSubmit')[0]);
        // 获取<meta>标签中封装的_csrf信息
        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        $.ajax({
            type: 'POST',
            url: '/admin/article/uploadImage',
            //url: /*[[@{/admin/article/uploadImage}]]*/,
            data: formData,
            async: true,
            contentType: false,
			//发送CSRF
            beforeSend : function(xhr) {
                xhr.setRequestHeader(header, token);
            },
            
            processData: false,
            //dataType: 'json',
            success: function (result) {
                alert(result);
            },
            error: function () {
                //
            }
        });

    }
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务