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

添加Spring Security过滤器后所有请求返回404如何解决

问题根因

你的Spring Security配置存在顺序错误,同时路径匹配规则使用不当,导致请求无法正常进入控制器层,核心问题如下:

  1. antMatcher("/admin/**")配置位置错误:该方法用于指定当前Security过滤器链仅拦截/admin/**前缀的请求,放在授权规则之后会导致规则优先级混乱,非/admin/**的请求没有对应认证逻辑支撑,无法完成认证流程。
  2. 授权规则顺序错误:先声明anyRequest().authenticated()要求所有请求必须认证,但仅给/admin/**路径绑定了自定义认证过滤器,其他路径的请求没有可执行的认证逻辑,被直接拦截无法进入控制器。
  3. 混合继承冲突:你同时继承WebSecurityConfigurerAdapter和实现WebMvcConfigurer,如果没有特殊MVC自定义需求,混合实现容易导致Spring上下文路径映射规则冲突。
修复方案

根据你的业务需求选择对应配置调整方案:

方案1:所有请求都走自定义认证逻辑

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.cors()
            .and()
            .httpBasic().disable()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            // 先绑定自定义过滤器,对所有路径生效
            .addFilterBefore(new AuthenticationFilter(adminAuthClient, myUserDetailsService),
                    UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .anyRequest()
            .authenticated();
}

方案2:仅/admin/**路径需要认证,其他路径直接放行

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.cors()
            .and()
            .httpBasic().disable()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            // 先指定当前过滤器链仅匹配/admin/**路径
            .antMatcher("/admin/**")
            .addFilterBefore(new AuthenticationFilter(adminAuthClient, myUserDetailsService),
                    UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .anyRequest()
            .authenticated();
}
额外检查项
  • 确认AuthenticationFilter认证成功后,已将生成的Authentication对象存入SecurityContextHolder,示例逻辑如下:
// 认证通过后执行
SecurityContextHolder.getContext().setAuthentication(validatedToken);
// 继续执行后续过滤器链,进入控制器
filterChain.doFilter(request, response);
  • 确认AuthenticationFilter认证失败的逻辑是直接写入响应返回401/403状态码,没有做请求转发/重定向到不存在的路径,避免触发404错误。
  • 如无自定义MVC配置需求,移除HttpSecurityConfig类实现的WebMvcConfigurer接口,避免路径映射规则被覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:24:04