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不生效内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
如何在SpringBoot项目中集成SpringSecurity进行权限管理
在本文中,我们将讨论如何在Spring Boot项目中集成权限管理,我们将使用Spring Security框架,这是一个专门用于实现安全性功能的框架,包括认证和授权,需要的朋友可以参考下2023-07-07


最新评论