Spring Security过滤器链白名单配置异常:测试返回401未授权
问题:Spring Boot Security 3.1.5白名单路径返回401未授权
使用Spring Boot Security 3.1.5构建安全过滤器链,已将/ping/getEnvironment配置为无需认证的白名单路径,但测试时该接口返回401未授权状态码,而非预期的200。以下是相关代码及错误信息:
依赖配置
implementation 'org.springframework.boot:spring-boot-starter-security:3.1.5'
过滤器链配置代码
private static final String[] WHITE_LIST_URL = {"/ping/getEnvironment"}; public SecurityFilterChain securityFilterChain(HttpSecurity http) { try { http.csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL) .permitAll() .anyRequest() .authenticated()) .sessionManagement(session -> session.sessionCreationPolicy(STATELESS)) .authenticationProvider(authenticationProvider) .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } catch (Exception e) { throw new IllegalStateException("Not able to build security filter chain", e); } }
测试代码
@Test void getEnvironmentTest() throws Exception { String rawResponse = mockMvc.perform(MockMvcRequestBuilders.get("/ping/getEnvironment")) .andExpect(MockMvcResultMatchers.status() .isOk()) .andReturn() .getResponse() .getContentAsString(); ObjectMapper objectMapper = new ObjectMapper(); PingResponse pingResponse = objectMapper.readValue(rawResponse, PingResponse.class); Assertions.assertNotNull(pingResponse); }
错误响应
MockHttpServletResponse: Status = 401 Error message = Unauthorized Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", WWW-Authenticate:"Basic realm="Realm"", X-Content-Type-Options:"nosniff", X-XSS-Protection:"0", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"] Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] Status Expected :200 Actual :401
可能的解决方向
- 核对路径匹配:确认实际请求路径和白名单完全一致,无大小写差异、上下文前缀等问题。可尝试显式使用Ant匹配器确保精确匹配:
req.requestMatchers(AntPathRequestMatcher.antMatcher("/ping/getEnvironment")).permitAll() - 排查JWT过滤器干扰:检查
jwtAuthFilter是否在白名单路径前执行了认证逻辑,可在过滤器内部跳过白名单路径的处理:@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (Arrays.asList(WHITE_LIST_URL).contains(request.getRequestURI())) { filterChain.doFilter(request, response); return; } // 原有JWT认证逻辑 } - 确认过滤器链优先级:若存在多个
SecurityFilterChainBean,通过@Order(1)注解确保当前配置优先执行。 - 禁用默认Basic认证:错误响应中的Basic认证头表明可能触发了默认逻辑,可显式禁用:
http.httpBasic(AbstractHttpConfigurer::disable)
内容的提问来源于stack exchange,提问作者Bogdan Oloeriu
相关产品推荐
相关产品推荐

