Spring Security新版本配置迁移失败:登录接口返回401未授权
Spring Security 新版本迁移中登录接口401问题排查与解决
问题原因分析
你遇到的/authentication/login返回401的问题,大概率是以下两个原因之一:
路径匹配规则不兼容
旧版的antMatchers使用Ant风格路径匹配,而新版requestMatchers默认采用Servlet规范的路径匹配逻辑,两者对通配符、路径后缀的处理存在差异。如果Endpoints.PUBLIC_ENDPOINTS中的路径格式(比如是否带/**、是否精确匹配)没有适配新版规则,会导致登录接口没有被正确标记为公开。JWT过滤器未跳过公开接口
你的jwtRequestFilter可能在所有请求中都执行了JWT校验,包括公开接口。即使Security配置里标记了permitAll,过滤器如果提前拦截并校验JWT,依然会返回401。
修正后的配置示例
方案1:适配路径匹配规则
明确使用Ant风格匹配器,和旧版antMatchers行为保持一致:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .cors(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth // 用AntPathRequestMatcher明确指定匹配规则 .requestMatchers( Arrays.stream(Endpoints.PUBLIC_ENDPOINTS) .map(AntPathRequestMatcher::antMatcher) .toArray(RequestMatcher[]::new) ).permitAll() .anyRequest().authenticated() ) .exceptionHandling(ex -> ex.authenticationEntryPoint(jwtAuthenticationEntryPoint)) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); }
方案2:修改JWT过滤器逻辑
在jwtRequestFilter的doFilterInternal方法中,先判断请求路径是否属于公开接口,是则直接放行:
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String requestUri = request.getRequestURI(); AntPathMatcher pathMatcher = new AntPathMatcher(); // 检查是否为公开接口,是则跳过JWT校验 for (String publicEndpoint : Endpoints.PUBLIC_ENDPOINTS) { if (pathMatcher.match(publicEndpoint, requestUri)) { filterChain.doFilter(request, response); return; } } // 非公开接口执行JWT校验逻辑 String jwtToken = extractJwtFromRequest(request); // ... 后续校验逻辑 }
新版SecurityFilterChain配置要点
- 链式调用优先使用lambda表达式(替代旧版的
.and()链式),代码更简洁易读 - 明确指定请求匹配器类型(
AntPathRequestMatcher/MvcRequestMatcher),避免默认匹配规则带来的兼容问题 - 过滤器逻辑必须和Security配置配合,公开接口要同时在配置中
permitAll且在过滤器中跳过校验 - 保持会话策略为
STATELESS,符合JWT无状态认证的设计
内容的提问来源于stack exchange,提问作者glethien
相关产品推荐
相关产品推荐

