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

Spring Boot3/Spring Security6:非安全端点跳过无效Authorization头认证

问题分析

你遇到的核心问题是Spring Security OAuth2 Resource Server过滤器默认会拦截所有携带Authorization: Bearer头的请求,哪怕该路径已经配置了permitAll。所以当请求/non-oauth/**或/unsecured时,只要带了遗留服务器签发的Token,OAuth2过滤器会尝试校验这个Token——因为无法识别(不是Keycloak签发的),就会直接拒绝请求。

解决方案

要解决这个问题,只需要让OAuth2 Resource Server的过滤器仅作用在需要OAuth2认证的路径上,也就是你的ntKeycloakAuthProperties.getPaths()配置的路径(比如/oauth2/**)。这样其他路径的请求,哪怕带了Bearer Token,也不会触发OAuth2的认证流程。

修改你的SecurityFilterChain配置,在oauth2ResourceServer块中添加requestMatchers指定生效路径:

@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity, NTKeycloakAuthProperties ntKeycloakAuthProperties, HandlerExceptionResolver handlerExceptionResolver) throws Exception {

    return httpSecurity
            .csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> {
                if (ntKeycloakAuthProperties.getPaths() == null) {
                    log.warn("[Keycloak Auth] No secure paths have been added to configuration");
                } else {
                    ntKeycloakAuthProperties.getPaths().forEach(path ->
                            authorizationManagerRequestMatcherRegistry.requestMatchers(path).authenticated());
                }

                authorizationManagerRequestMatcherRegistry.requestMatchers("/**").permitAll();
            })
            .oauth2ResourceServer(httpSecurityOAuth2ResourceServerConfigurer -> {
                // 核心修改:只对指定的OAuth2路径启用认证流程
                httpSecurityOAuth2ResourceServerConfigurer.requestMatchers(ntKeycloakAuthProperties.getPaths());
                
                httpSecurityOAuth2ResourceServerConfigurer.authenticationManagerResolver(
                        new JwtIssuerAuthenticationManagerResolver(ntKeycloakAuthProperties.getIssuers()));
                httpSecurityOAuth2ResourceServerConfigurer.authenticationEntryPoint(
                        new BearerTokenProblemDetailsAuthenticationEntryPoint(handlerExceptionResolver));
            })
            .build();
}

效果验证

修改后:

  • 请求/unsecured:无论是否带Token,都会直接放行(因为permitAll,且OAuth2过滤器不生效);
  • 请求/oauth2/**:只有携带Keycloak签发的有效Token才会被允许,无效/非Keycloak Token会被拒绝;
  • 请求/non-oauth/**:OAuth2过滤器不介入,由你已实现的遗留认证过滤器处理Token校验,符合预期。

额外说明

如果你的遗留认证过滤器是基于Spring的Filter实现,需要确保它的执行顺序在Spring Security过滤器之后(或者根据实际需求调整),避免和OAuth2过滤器的逻辑冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:35:26