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

如何在OAuth2/2.1 Spring Boot资源服务器中获取Scope与Roles

如何在Spring Boot OAuth2/2.1资源服务器中获取Token中的Roles

默认情况下,Spring Boot OAuth2资源服务器只会将Token Introspect结果里的scope字段解析为GrantedAuthority,要同时获取roles字段,需要自定义Token解析逻辑:

  1. 自定义OpaqueTokenIntrospector
    因为你使用的是Token Introspection(不透明令牌),所以需要重写OpaqueTokenIntrospector的解析逻辑,在默认解析完成后手动提取roles并转换为权限:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class ResourceServerConfig {

    @Bean
    public OpaqueTokenIntrospector customOpaqueTokenIntrospector() {
        // 初始化默认的Nimbus解析器,替换为你的实际配置
        NimbusOpaqueTokenIntrospector delegate = new NimbusOpaqueTokenIntrospector(
                "http://3.6.239.198:9000/oauth2/introspect",
                "1",
                "your-client-secret" // 如果你的客户端有密钥,替换为实际值
        );

        return token -> {
            // 先执行默认解析
            var authenticated = delegate.introspect(token);
            // 提取introspect结果中的roles字段
            List<String> roles = authenticated.getClaimAsStringList("roles");
            
            if (roles != null && !roles.isEmpty()) {
                // 将roles转换为GrantedAuthority,可根据需求添加ROLE_前缀
                Collection<GrantedAuthority> roleAuthorities = roles.stream()
                        .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                        .collect(Collectors.toList());
                // 将角色权限合并到已有权限中
                authenticated.getAuthorities().addAll(roleAuthorities);
            }
            return authenticated;
        };
    }
}
  1. 验证效果
    配置完成后,再次调用以下代码:
Authentication authentication = getAuthentication();
System.out.println(authentication.getAuthorities());

就能同时看到scope对应的权限(如SCOPE_read)和roles转换后的权限(如ROLE_user)。

注意:如果你的角色不需要ROLE_前缀,直接使用new SimpleGrantedAuthority(role)即可;同时要确保配置的introspect端点、client_id和密钥与授权服务器一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:07:41