SpringSecurity抛出异常但AccessDeniedHandler不生效

发布于:2025-02-10 ⋅ 阅读:(40) ⋅ 点赞:(0)

文章目录

复现

@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;
}
//...