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;
}
//...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lucky_Turtle

感谢您的打赏,作者会多多努力的

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值