You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3 + Thymeleaf自定义403错误页面配置问题

解决方案

1. 修复请求匹配器的创建方式

Spring Security 6中,AntPathRequestMatcher的构造逻辑已调整,推荐使用静态工厂方法替代旧构造调用:

// 旧代码
new AntPathRequestMatcher("/**")
// 替换为
AntPathRequestMatcher.antMatcher("/**")

2. 放行自定义403页面路径

在authorizeHttpRequests的permitAll列表中添加自定义403页面的路径(比如"/403"),避免跳转时被拦截导致循环:

.requestMatchers("/",
        "/login",
        "/403", // 新增该行,允许匿名访问403页面
        "/css/**",
        "/js/**",
        "/images/**",
        "/static/favicon.ico",
        "/favicon.ico",
        "/fullscreen").permitAll()

3. 调整异常处理配置

根据业务需求选择以下配置方式:

方式一:全局覆盖认证入口逻辑

若需要所有未认证请求直接返回自定义403页面(而非默认跳转登录页),直接设置全局入口点:

.exceptionHandling(handling -> handling
        .authenticationEntryPoint(new Http403ForbiddenEntryPoint())
        .accessDeniedHandler((request, response, ex) -> {
            // 处理已登录用户权限不足的403场景
            response.sendRedirect("/403");
        })
)

方式二:针对特定路径配置入口点

若仅需对指定路径应用自定义逻辑,保留defaultAuthenticationEntryPointFor并修复匹配器:

.exceptionHandling(handling -> handling
        .defaultAuthenticationEntryPointFor(
                new Http403ForbiddenEntryPoint(),
                AntPathRequestMatcher.antMatcher("/**")
        )
        .accessDeniedHandler((request, response, ex) -> {
            response.sendRedirect("/403");
        })
)

4. 验证自定义EntryPoint实现

确保Http403ForbiddenEntryPoint的逻辑正确,示例实现如下:

public class Http403ForbiddenEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 跳转到自定义403页面
        response.sendRedirect("/403");
        // 也可选择forward方式(需确保视图解析器能识别路径)
        // response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        // request.getRequestDispatcher("/403").forward(request, response);
    }
}

关键注意点

  • 未认证请求触发AuthenticationEntryPoint(对应401状态),已登录但权限不足触发AccessDeniedHandler(对应403状态),需按需分别配置。
  • 必须确保自定义错误页面路径加入permitAll,否则会触发拦截循环,导致显示默认错误界面。

内容的提问来源于stack exchange,提问作者larjae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:35:32