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

Okta Spring项目如何主动覆盖401响应并返回404状态码

实现方案

你可以直接通过扩展Spring Security的异常处理逻辑实现需求,无需调整Okta侧配置,ControllerAdvice无法捕获该异常的原因是Spring Security的过滤器链执行优先级高于Spring MVC的请求分发逻辑,异常触发时还没进入Controller的处理流程。

修改后的配置代码如下:

@Configuration
static class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                // 放行首页
                .antMatchers("/").permitAll()
                // 其余接口需要认证
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer().jwt()
                .and()
                // 自定义安全异常处理
                .exceptionHandling()
                // 未认证场景直接返回404
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                })
                // 按需添加:权限不足场景也返回404
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                });

        // 原有Okta 401配置可以删除,自定义EntryPoint优先级更高
        // Okta.configureResourceServer401ResponseBody(http);
    }
}

补充说明

  • 核心逻辑是替换默认的AuthenticationEntryPoint实现:Spring Security默认的未认证处理逻辑要么返回401,要么重定向到登录页,我们自定义实现后直接将响应状态码设为404即可。
  • 目前Okta官方的Spring Boot Starter没有提供直接修改未认证响应码的配置项,上述Spring Security原生扩展方式是最高效的实现方案,不需要额外引入其他依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:36:03