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

Spring Authorization Server 0.3.1:如何设置非Client-ID的令牌受众

在Spring Authorization Server 0.3.1中自定义令牌受众

针对Spring Authorization Server 0.3.1默认将Client-ID设为令牌受众的问题,你可以通过以下两种方式设置自定义受众:

方法一:自定义JWT Token Customizer

通过实现OAuth2TokenCustomizer<JwtEncodingContext>来修改JWT的aud声明,支持全局或针对特定客户端调整受众:

@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer() {
    return context -> {
        // 方式1:在默认Client-ID受众基础上添加自定义受众
        Set<String> audiences = new HashSet<>(context.getClaims().getAudience());
        audiences.add("your-custom-audience-1");
        audiences.add("your-custom-audience-2");
        
        // 方式2:完全替换默认受众(去掉Client-ID)
        // Set<String> audiences = new HashSet<>(Arrays.asList("your-custom-audience"));
        
        context.getClaims().audience(audiences);
    };
}

这个Bean会自动融入JWT生成流程,在令牌编码阶段修改受众字段。

方法二:针对特定客户端配置受众

如果只需为某个客户端设置自定义受众,可以在ClientRegistration配置中直接指定:

@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
    return new InMemoryClientRegistrationRepository(
        ClientRegistration.withRegistrationId("your-client")
            .clientId("your-client-id")
            .clientSecret("your-client-secret")
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .redirectUri("http://localhost:8080/login/oauth2/code/your-client")
            .scope("openid", "profile")
            // 配置该客户端的专属受众
            .audience(Arrays.asList("client-specific-aud-1", "client-specific-aud-2"))
            .build()
    );
}

注意:这种方式下,生成的令牌受众会同时包含Client-ID和你指定的自定义值,如果需要完全移除Client-ID,建议结合方法一使用。

额外说明

以上方法仅适用于JWT格式的令牌;如果使用不透明令牌(Opaque Token),需自定义TokenStore来管理受众信息,因为不透明令牌的元数据存储在服务器端而非令牌本身。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:55:08