Spring Security自定義失敗處理器問題
Spring Security自定義失敗處理器
我們還希望在認證失敗或者是授權(quán)失敗的情況下也能和我們的接口一樣返回相同結(jié)構(gòu)的json,這樣可以讓前端能對響應(yīng)進行統(tǒng)一的處理。要實現(xiàn)這個功能我們需要知道SpringSecurity的異常處理機制。
在SpringSecurity中,如果我們在認證或者授權(quán)的過程中出現(xiàn)了異常會被ExceptionTranslationFilter捕獲到。在ExceptionTranslationFilter中會去判斷是認證失敗還是授權(quán)失敗出現(xiàn)的異常。
- 如果是認證過程中出現(xiàn)的異常會被封裝成AuthenticationException然后調(diào)用AuthenticationEntryPoint對象的方法去進行異常處理。
- 如果是授權(quán)過程中出現(xiàn)的異常會被封裝成AccessDeniedException然后調(diào)用AccessDeniedHandler對象的方法去進行異常處理。
所以如果我們需要自定義異常處理,我們只需要自定義AuthenticationEntryPoint和AccessDeniedHandler然后配置SpringSecurity即可。
在Spring Security中,你可以通過實現(xiàn)特定的接口來自定義認證失敗處理器(AuthenticationFailureHandler)和授權(quán)失敗處理器(AccessDeniedHandler)。以下是如何分別自定義它們的步驟:
一、自定義認證失敗處理器(AuthenticationFailureHandler)
- 1.1創(chuàng)建自定義的
AuthenticationFailureHandler
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
// 在這里處理認證失敗的情況
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("登錄失敗: " + exception.getMessage());
}
}- 1.2在Spring Security配置中使用你的自定義認證失敗處理器
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ... 其他配置 ...
.formLogin()
.failureHandler(new CustomAuthenticationFailureHandler()) // 設(shè)置自定義認證失敗處理器
// ... 其他表單登錄配置 ...
// ... 其他HTTP安全配置 ...
;
}二、自定義授權(quán)失敗處理器(AccessDeniedHandler)
- 2.1創(chuàng)建自定義的
AccessDeniedHandler
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
// 在這里處理授權(quán)失敗的情況
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().write("權(quán)限不足: " + accessDeniedException.getMessage());
}
}- 2.2在Spring Security配置中使用你的自定義授權(quán)失敗處理器
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ... 其他配置 ...
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler()) // 設(shè)置自定義授權(quán)失敗處理器
// ... 其他異常處理配置 ...
// ... 其他HTTP安全配置 ...
;
}三、實戰(zhàn)
我們還希望在認證失敗或者是授權(quán)失敗的情況下也能和我們的接口一樣返回相同結(jié)構(gòu)的json,這樣可以讓前端能對響應(yīng)進行統(tǒng)一的處理。要實現(xiàn)這個功能我們需要知道SpringSecurity的異常處理機制。
在SpringSecurity中,如果我們在認證或者授權(quán)的過程中出現(xiàn)了異常會被ExceptionTranslationFilter捕獲到。在ExceptionTranslationFilter中會去判斷是認證失敗還是授權(quán)失敗出現(xiàn)的異常。
- 如果是認證過程中出現(xiàn)的異常會被封裝成AuthenticationException然后調(diào)用AuthenticationEntryPoint對象的方法去進行異常處理。
- 如果是授權(quán)過程中出現(xiàn)的異常會被封裝成AccessDeniedException然后調(diào)用AccessDeniedHandler對象的方法去進行異常處理。
所以如果我們需要自定義異常處理,我們只需要自定義AuthenticationEntryPoint和AccessDeniedHandler然后配置SpringSecurity即可。
(com.sangeng.handler)
- 自定義認證失敗處理器:
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse
response, AuthenticationException authException) throws IOException,
ServletException {
ResponseResult result = new
ResponseResult(HttpStatus.UNAUTHORIZED.value(), "認證失敗請重新登錄");
String json = JSON.toJSONString(result);
WebUtils.renderString(response, json);
}
}- 自定義授權(quán)失敗處理器:
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException,
ServletException {
ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(),
"權(quán)限不足");
String json = JSON.toJSONString(result);
WebUtils.renderString(response, json);
}
}- 修改配置類:
@Configuration //配置類
@EnableWebSecurity // 開啟Spring Security的功能 代替了 implements WebSecurityConfigurerAdapter
public class SecurityConfig {
@Autowired
AuthenticationConfiguration authenticationConfiguration;//獲取AuthenticationManager
@Autowired
JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Autowired
AccessDeniedHandlerImpl accessDeniedHandler;
@Autowired
AuthenticationEntryPointImpl authenticationEntryPoint;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
/**
* 配置Spring Security的過濾鏈。
*
* @param http 用于構(gòu)建安全配置的HttpSecurity對象。
* @return 返回配置好的SecurityFilterChain對象。
* @throws Exception 如果配置過程中發(fā)生錯誤,則拋出異常。
*/
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// 禁用CSRF保護
.csrf(csrf -> csrf.disable())
// 設(shè)置會話創(chuàng)建策略為無狀態(tài)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// 配置授權(quán)規(guī)則 指定user/login路徑.允許匿名訪問(未登錄可訪問已登陸不能訪問). 其他路徑需要身份認證
.authorizeHttpRequests(auth -> auth.requestMatchers("/user/login").anonymous().anyRequest().authenticated())
//開啟跨域訪問
.cors(AbstractHttpConfigurer::disable)
// 添加JWT認證過濾器
.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
// 配置異常處理
.exceptionHandling(exception -> exception.accessDeniedHandler(accessDeniedHandler).authenticationEntryPoint(authenticationEntryPoint));
// 構(gòu)建并返回安全過濾鏈
return http.build();
}注意事項
- 確保你的認證和授權(quán)失敗處理器都正確實現(xiàn)了相應(yīng)的接口,并且正確設(shè)置了它們的狀態(tài)碼和響應(yīng)內(nèi)容。
- 你可以將你的自定義處理器作為Spring Bean注入到你的配置中,而不是直接在配置方法中創(chuàng)建新的實例。這樣可以更好地管理你的Spring應(yīng)用程序中的bean。
- 在處理認證和授權(quán)失敗時,你可能希望返回JSON而不是純文本響應(yīng),特別是在構(gòu)建RESTful API時。為此,你可以使用
@ResponseBody注解或ResponseEntity類來構(gòu)建JSON響應(yīng)。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于HashMap的put方法執(zhí)行全過程
這篇文章主要介紹了關(guān)于HashMap的put方法執(zhí)行全過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
java開發(fā)gui教程之jframe監(jiān)聽窗體大小變化事件和jframe創(chuàng)建窗體
這篇文章主要介紹了java開發(fā)gui教程中jframe監(jiān)聽窗體大小變化事件和jframe創(chuàng)建窗體的示例,需要的朋友可以參考下2014-03-03
解決Java項目啟動報錯:Logback?configuration?error?detected:問題
這篇文章主要介紹了解決Java項目啟動報錯:Logback?configuration?error?detected:問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
實例解決Java異常之OutOfMemoryError的問題
在本篇文章中,我們給大家分享了關(guān)于解決Java異常之OutOfMemoryError的問題的方法,有此需要的朋友們學習下。2019-02-02
Spring boot jpa 刪除數(shù)據(jù)和事務(wù)管理的問題實例詳解
這篇文章主要介紹了Spring boot jpa 刪除數(shù)據(jù)和事務(wù)管理的問題實例詳解,涉及業(yè)務(wù)場景的一些知識和遇到的的問題,需要的朋友可以參考。2017-09-09
Java?Selenium實現(xiàn)修改打開頁面窗口大小
Selenium是一個強大的自動化測試工具,支持多種編程語言和瀏覽器,本文將詳細介紹如何使用Java?Selenium來修改打開頁面窗口的大小,需要的可以參考下2025-01-01

