1. 程式人生 > 其它 >spring security permitAll不生效

spring security permitAll不生效

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發現tokenBasic Og== 強烈建議不要用某些介面測試工具(xxxpost) 大坑

3 小結

當我們使用了permitAll時 記住authorizeRequestsBasicAuthenticationFilter的後面(告訴面試官 我的某某學妹畢業了想來我公司實習 挺優秀的 麻煩通融通融放行白 面試官問 具體資訊 就這樣愉快的進來了) 或者直接忽略web.ignoring().antMatchers(...) 我跳出五行 不在過濾器鏈中混了
慎用某些介面測試工具