SpringSecurity抛出异常但AccessDeniedHandler不生效的解决
作者:Lucky_Turtle
本文主要介绍了SpringSecurity抛出异常但AccessDeniedHandler不生效的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
复现
@Bean
public 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 Denied
at 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;
}
//...到此这篇关于SpringSecurity抛出异常但AccessDeniedHandler不生效的解决的文章就介绍到这了,更多相关SpringSecurity AccessDeniedHandler不生效内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
