自定义异常处理
2023年2月16日小于 1 分钟约 246 字
TODO 为啥不用全局异常捕获?
在 Spring Security 中,如果在认证或授权的过程中出现了异常,会被ExceptionTranslationFilter
捕获到,其中会判断具体是认证失败还是授权失败。
如果是认证过程中的异常,会被封装成
AuthenticationException
然后调用AuthenticationEntryPoint
对象的方法去进行异常处理;public interface AuthenticationEntryPoint { void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException; }
如果是授权过程中的异常,会被封装成
AccessDeniedException
然后调用AccessDeniedHandler
对象的方法去进行异常处理;public interface AccessDeniedHandler { void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException; }
所以,如果我们需要自定义异常处理,只需要定义AuthenticationEntryPoint
和AccessDeniedHandler
,然后将实现类配置给 Spring Security 即可。
自定义两个接口的实现类:不必多言;
配置给 Spring Security 的方式为:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // ... http.exceptionHandling() .authenticationEntryPoint(xxx) .accessDeniedHandler(yyy); } // ... }