0 環境
- 系統:win10
- 編輯器:IDEA
1 問題描述
1 部分代碼
securityConfig http
http
// 攔截請求,創建了FilterSecurityInterceptor攔截器
.authorizeRequests()
// 允許
// "/login",
// "/logout",
// "/captcha",
// "/favicon.ico"
.antMatchers(URL_WHITELIST).permitAll()
.anyRequest().authenticated()
.and()
// 在用戶密碼認證前 認證驗證碼是否正確
//.addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
// token驗證 繼承BasicAuthenticationFilter
.addFilter(jwtAuthenticationFilter());
當我進入登陸頁 獲取驗證碼
http://127.0.0.1:8081/captcha
不需要用戶認證直接放行 但現在不生效 提示token異常
繼承BasicAuthenticationFilter類目的 每次訪問業務都需要攜帶token 錯誤提示token異常 過期等
2 解決
1 原理
FilterSecurityInterceptor攔截器排在最后 那么authorizeRequests在BasicAuthenticationFilter之后執行
2 驗證啟動順序
繼承BasicAuthenticationFilter類 JwtAuthenticationFilter
⇒ 驗證token(請求頭Authorization)
AuthController
==> 獲取驗證碼captcha
也就是說JwtAuthenticationFilter
這里遇到前面的url直接放行或者不在過濾器鏈中 直接忽略
1 在繼承BasicAuthenticationFilter類中 url直接放行
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
.....
// 假如不需要token的判斷 根據自己的需要編寫
if(request.getServletPath().equals("/captcha")){
chain.doFilter(request, response);
return;
}
....
}
2 不在過濾器鏈中 直接忽略
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("...","..."....需要過濾的url);
}
3 debug
我需要判斷token為空的判斷 在放行 看代碼沒毛病 沒找到問題 但接口測試工具(非postman) 測試始終過不去 后來debug發現
token
為Basic Og==
強烈建議不要用某些接口測試工具(xxxpost) 大坑
3 小結
當我們使用了
permitAll
時 記住authorizeRequests
在BasicAuthenticationFilter
的后面(告訴面試官 我的某某學妹畢業了想來我公司實習 挺優秀的 麻煩通融通融放行白 面試官問 具體信息 就這樣愉快的進來了) 或者直接忽略web.ignoring().antMatchers(...)
我跳出五行 不在過濾器鏈中混了
慎用某些接口測試工具