springsecurity配置csrf,ajax发送post请求访问

 找了半天参差不齐的文章,最终解决了,为了防止别人被误导,实测能行的配置

security配置

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers("/login.html", "/login", "/logout")
                .and()
                .authorizeRequests()
                .antMatchers("/login.html", "/login").permitAll()
                .anyRequest().authenticated()

                .and()
                .formLogin()
                .loginPage("/login.html").loginProcessingUrl("/login")
         
                .defaultSuccessUrl("/")
                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST"))
                //使得session失效
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .deleteCookies("XSRF-TOKEN")
                //清除认证信息
                .clearAuthentication(true)
                .logoutSuccessUrl("/login.html").permitAll()


                .and()
                .sessionManagement()
                .invalidSessionUrl("/login.html")
                .maximumSessions(1).sessionRegistry(new SessionRegistryImpl())
    }

  引入

<script type="text/javascript" src="https://cdn.staticfile.org/jquery-cookie/1.0/jquery.cookie.js"></script>
        //获取浏览器中的cookie
        let _csrf = $.cookie('XSRF-TOKEN');
        $.ajax({
            url:"/book/search",
            async: false,
            type: 'post',
            //添加csrf请求头 网上很多错误的headers配置
            headers:{"X-XSRF-TOKEN":_csrf, "Content-Type":"application/json"},
            withCredentials: true,
            ContentType: 'application/json; utf-8',
            //自己定义请求体数据
            data: JSON.stringify({"key":"data"}),
            dataType: 'json',
            //按照自己的返回体自行配置
            success: (response) => {
                if (response) {
                    if (response.code === 0) {
                        console.log(response.data.data);
                    }
                    else {
                        alert(response.message);
                    }
                } else alert("服务器后端未启动");
            }
        })

这样就可以了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值