SpringSecurity抛出异常但AccessDeniedHandler不生效
文章目录
- 复现
- 原因
复现
@Beanpublic SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception {//...//异常http.exceptionHandling(except -> {except.authenticationEntryPoint(new SecurityAuthenticationEntryPoint());except.accessDeniedHandler((request, response, e) -> { //请求未授权的接口//创建结果对象HashMap result = new HashMap();result.put("code", -1);result.put("message", "没有权限");//转换成json字符串String json = JSON.toJSONString(result);//返回响应response.setContentType("application/json;charset=UTF-8");response.getWriter().println(json);});//...});
还是抛出异常
org.springframework.security.access.AccessDeniedException: Access Deniedat org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor.attemptAuthorization(AuthorizationManagerBeforeMethodInterceptor.java:256) ~[spring-security-core-6.2.1.jar:6.2.1]at org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor.invo
原因
@RestControllerAdvice
全局异常拦截到了直接返回,注释掉
或者采用
import org.springframework.security.access.AccessDeniedException
//...
@ExceptionHandler(AccessDeniedException.class)
public void accessDeniedException(AccessDeniedException e) throws AccessDeniedException {throw e;
}
//...