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

Spring Security多场景HttpSecurity配置:无Bearer Token请求异常跳转问题

解决方案

问题根源

当前filterChainJWT的securityMatchers仅匹配携带Bearer Token的请求,未携带Token的/api/getuser请求会落入filterChainLogin,触发Active Directory登录跳转。要实现未携带Token时返回401,需让所有/api/**请求优先进入JWT过滤器链,在链内处理未授权场景。

修改后的配置代码

1. 调整JWT过滤器链的匹配规则

@Bean
@Order(1)
public SecurityFilterChain filterChainJWT(HttpSecurity http) throws Exception {
    // 匹配所有/api前缀的请求,确保接口请求都走JWT校验链
    http.securityMatchers(matcher -> matcher.requestMatchers("/api/**"));

    http.exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler) // 未授权时返回401
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers(HttpMethod.GET, "/signout").permitAll()
                    .anyRequest().authenticated()
            )
            .csrf().disable();

    http.authenticationProvider(customAuthenticationProvider);
    http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

2. 调整AD登录过滤器链的匹配范围

@Bean
@Order(2)
public SecurityFilterChain filterChainLogin(HttpSecurity http) throws Exception {
    // 排除/api前缀的请求,仅处理页面类登录请求
    http.securityMatchers(matcher -> matcher.requestMatchers(request -> 
            !request.getRequestURI().startsWith("/api/")))
            .apply(AadWebApplicationHttpSecurityConfigurer.aadWebApplication())
            .and()
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers(HttpMethod.GET, "/signout").permitAll()
                    .anyRequest().authenticated()
            )
            .csrf().disable();
    return http.build();
}

3. 确保unauthorizedHandler正确返回401响应

@Component
public class UnauthorizedHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getOutputStream(), Map.of(
                "code", 401,
                "message", "未携带有效Bearer Token,禁止访问"
        ));
    }
}

效果说明

  • 场景1:GET请求/login仍由filterChainLogin处理,正常跳转AD登录页面。
  • 场景2:携带Bearer Token的POST请求/api/getuser进入filterChainJWT,完成校验后正常响应。
  • 场景3:未携带Bearer Token的POST请求/api/getuser进入filterChainJWT,由unauthorizedHandler返回401 JSON响应,不再跳转AD登录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 21:12:27