我是用ajax方式登陸的
js代碼:
$.ajax({
url: ajaxUrl + "/login_entry",
type:"post",
data:form.serialize(),
success:function (result) {
if(result.state==000000){
console.log("成功了");
var token = result.data.access_token;
localStorage.token=token;
window.location.href=https://bbs.csdn.net/topics/ajaxUrl +"/index";
}else{
console.log("失敗了"+result.message);
}
},
error:function () {
console.log("error");
}
java代碼:
@Override
protected void configure(HttpSecurity http) throws Exception {
//定制授權規則
http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()
.antMatchers("/inspinia_admin-v2.5/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_PAGE)
.loginProcessingUrl(LOGIN_ENTRY)
.successHandler(myAuthenticationSuccessHandler)
.failureHandler(myAuthenticationFailHander)
.permitAll()
.and()
.exceptionHandling(),
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(myAccessDeniedHandler)
.and()
.logout()
.logoutSuccessUrl(LOGIN_PAGE)
.logoutSuccessHandler(myLogoutSuccessHandler)
.permitAll();
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
http.addFilterBefore(myUsernamePasswordAuthenticationFilter, FilterSecurityInterceptor.class);
http.addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class);
}
點擊登陸按鈕的時候,會呼叫如上的js部分代碼,
1、有紅色部分代碼
這行代碼讓springsecurity不會創建session,也就無法保存認證結果了。導致第一次請求成功后,雖然生成了token,前端也成功獲取到了,也保存至localStorage了,但是接下來的頁面跳轉 window.location.href=https://bbs.csdn.net/topics/ajaxUrl +"/index";無法攜帶token。springsecurity就沒辦法根據token獲取用戶資訊了,所以springsecurity就覺得“小子,你沒有鑰匙,也不認識你,休想跨過此門”。然后就當作授權失敗處理,重定向到登陸頁面。另外如果是window.location.href這種方式,SecurityContextHolder.getContext().getAuthentication())這個是null,沒辦法在自定義tokenFilter中獲取用戶
2、沒有紅色部分
springsecurity會把認證結果放到SecurityContext中,然后再放到session中。由于/login_entry請求已經成功認證,以后可以從SecurityContext中獲取認證結果。所以其他的功能都可以實作。
出現這種情況的原因是頁面點擊一次登陸,會請求兩次。window.location.href無法攜帶第一次("/login_entry",)ajax請求回傳的token。
在網上查了很多,但都沒有出現這個情況,唯一相似的情況是跨域請求,但是我這個好像并不屬于跨域請求吧。都是請求127.0.0.1:8080。ip、埠都一樣。
我肯定有哪個地方寫錯,有沒有哪位大神指導一下啊。。。(^_^)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/102645.html
標籤:JavaScript
上一篇:小白求助!win10不小心把管理員賬戶改成來賓賬戶了!怎么改回去啊啊啊啊!
下一篇:現在建站用什么CMS好?
