Spring Security中Access Denied异常的自定义重定向处理方案
处理Spring 6中Access Denied异常并重定向到自定义静态页面
在Spring Security里,负责处理AccessDeniedException的核心过滤器是ExceptionTranslationFilter,它默认会使用DefaultAccessDeniedHandler返回403状态码。若要实现重定向到自定义静态页面,你需要替换这个默认处理器,具体操作如下:
1. 实现自定义AccessDeniedHandler
创建一个类实现AccessDeniedHandler接口,重写handle方法指定重定向路径:
import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import java.io.IOException; public class CustomAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { // 重定向到自定义403页面,假设页面位于static目录下的403.html response.sendRedirect("/403.html"); } }
2. 配置SecurityFilterChain替换默认处理器
在Spring Security配置类中,注入自定义的AccessDeniedHandler并替换默认实现,同时确保静态页面能被无权限访问:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.AccessDeniedHandler; @Configuration public class SecurityConfig { @Bean public AccessDeniedHandler customAccessDeniedHandler() { return new CustomAccessDeniedHandler(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth // 允许自定义403页面及其他静态资源无需认证即可访问 .requestMatchers("/403.html", "/css/**", "/js/**").permitAll() // 其他请求需认证 .anyRequest().authenticated() ) // 替换默认的AccessDeniedHandler .exceptionHandling(ex -> ex .accessDeniedHandler(customAccessDeniedHandler()) ); // 可根据需求添加表单登录、退出等其他配置 return http.build(); } }
3. 放置自定义静态页面
将你的自定义403页面(比如403.html)放在Spring Boot默认的静态资源目录下,例如src/main/resources/static/,Spring会自动识别并加载该页面。
关键注意事项
- 必须确保自定义静态页面的路径被配置为
permitAll,否则重定向时会再次触发权限拦截,导致循环重定向。 - Spring MVC的
@ControllerAdvice全局异常处理器无法捕获AccessDeniedException,因为该异常是在过滤器链阶段抛出的,尚未进入DispatcherServlet,因此必须使用Spring Security提供的AccessDeniedHandler来处理。
内容的提问来源于stack exchange,提问作者user14800584
相关产品推荐
相关产品推荐

