ControllerAdvice 拦截BasicHttpAuthenticationFilter 中的异常信息示例代码
时间: 2023-07-15 16:10:06 浏览: 47
假设你使用的是 Spring Boot 框架,以下是一个示例代码:
```java
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(BadCredentialsException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public String handleUnauthorized() {
return "Invalid username or password";
}
@ExceptionHandler(AuthenticationException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public String handleBadCredentials() {
return "Bad credentials";
}
}
public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {
public CustomBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
super.onUnsuccessfulAuthentication(request, response, failed);
throw failed;
}
}
```
在上述代码中,`CustomBasicAuthenticationFilter` 继承了 `BasicAuthenticationFilter`,并且在身份认证失败时将异常信息抛出。`CustomExceptionHandler` 中的 `@ExceptionHandler` 注解用于捕获 `BadCredentialsException` 和 `AuthenticationException` 异常,并且返回相应的错误信息。