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

如何在Spring Authorization Server中移除令牌端点的OAuth2AuthorizationCodeAuthenticationConverter

可行解决方案

要彻底移除默认的OAuth2AuthorizationCodeAuthenticationConverter,需要自定义OAuth2TokenEndpointFilter并替换SAS自动配置的实例,具体步骤如下:

1. 自定义TokenEndpointFilter,指定专属转换器列表

创建自定义Filter,仅保留需要的转换器,排除OAuth2AuthorizationCodeAuthenticationConverter:

@Component
public class CustomOAuth2TokenEndpointFilter extends OAuth2TokenEndpointFilter {
    public CustomOAuth2TokenEndpointFilter(AuthenticationManager authenticationManager, AuthorizationServerSettings authorizationServerSettings) {
        super(authenticationManager, authorizationServerSettings.getTokenEndpoint());
        // 自定义转换器列表,只保留需要的实现
        this.setAuthenticationConverter(new DelegatingAuthenticationConverter(Arrays.asList(
                new OAuth2RefreshTokenAuthenticationConverter(),
                new OAuth2ClientCredentialsAuthenticationConverter(),
                new OAuth2DeviceCodeAuthenticationConverter(),
                // 添加你的自定义转换器
                new CustomOAuth2AuthorizationCodeAuthenticationConverter()
        )));
    }
}

2. 在SecurityFilterChain中替换默认Filter

修改Security配置,移除SAS自动配置的OAuth2TokenEndpointFilter,替换为自定义实例:

@Bean
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, CustomOAuth2TokenEndpointFilter customTokenEndpointFilter) throws Exception {
    OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);

    var authorizationServerConfigurer = http.getConfigurer(OAuth2AuthorizationServerConfigurer.class);
    authorizationServerConfigurer.oidc(Customizer.withDefaults());

    // 替换默认的TokenEndpointFilter
    http.addFilterAt(customTokenEndpointFilter, OAuth2TokenEndpointFilter.class);

    return http.build();
}

3. 原方案失效原因

之前通过accessTokenRequestConverters添加自定义转换器的方式,只是将自定义逻辑插入到默认转换器列表的头部,默认的OAuth2AuthorizationCodeAuthenticationConverter依然存在于列表中。当请求到达时,DelegatingAuthenticationConverter会按顺序遍历转换器,默认转换器仍会被触发并抛出错误。而自定义Filter直接替换了整个转换器列表,从根源上排除了不需要的实现。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 15:49:56