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 Actuator未授权访问漏洞解决方案
工作的时候遇到过提示Spring Boot后端存在Actuator未授权访问漏洞,网上有很多详细的解释文章,在这里做一个简单的总结、介绍和分享,需要的朋友可以参考下2023-09-09
Spring中的@ExceptionHandler异常拦截器
这篇文章主要介绍了Spring中的@ExceptionHandler异常拦截器,Spring的@ExceptionHandler可以用来统一处理方法抛出的异常,给方法加上@ExceptionHandler注解,这个方法就会处理类中其他方法抛出的异常,需要的朋友可以参考下2024-01-01
Spring Boot集成Spring Cloud Security进行安全增强的方法
Spring Cloud Security是Spring Security的扩展,它提供了对Spring Cloud体系中的服务认证和授权的支持,包括OAuth2、JWT等,这篇文章主要介绍了Spring Boot集成Spring Cloud Security进行安全增强,需要的朋友可以参考下2024-11-11
eclipse里没有“Dynamic Web Project“这个选项的问题解决
本文主要介绍了eclipse里没有“Dynamic Web Project“这个选项的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-08-08
Java C++算法题解leetcode801使序列递增的最小交换次数
这篇文章主要为大家介绍了Java C++题解leetcode801使序列递增的最小交换次数示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-10-10


最新评论