找了半天参差不齐的文章,最终解决了,为了防止别人被误导,实测能行的配置
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("服务器后端未启动");
}
})
这样就可以了