拦截springsecurity 异常
时间: 2023-10-10 19:04:28 浏览: 48
可以通过实现Spring Security的异常处理接口来拦截Spring Security的异常。具体步骤如下:
1. 实现AuthenticationEntryPoint接口,该接口用于处理未登录的用户访问受保护资源时的异常。
```java
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
```
2. 实现AccessDeniedHandler接口,该接口用于处理已登录但没有访问权限的用户访问受保护资源时的异常。
```java
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
}
}
```
3. 配置异常处理器
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private CustomAccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler)
.and()
.formLogin()
.and()
.httpBasic()
.and()
.csrf().disable();
}
}
```
在上述配置中,通过调用exceptionHandling()方法来配置异常处理器,authenticationEntryPoint()方法用于配置未登录用户的异常处理器,accessDeniedHandler()方法用于配置已登录但没有权限的用户的异常处理器。
注意:在使用自定义异常处理器的情况下,应该禁用Spring Security的默认异常处理器(disable()方法)。