对于最新的稳定版本,请使用 Spring Security 6.5.3spring-doc.cadn.net.cn

OAuth 2.0 资源服务器不透明Tokens

内省的最小依赖关系

JWT 的最小依赖项中所述,大多数资源服务器支持都收集在spring-security-oauth2-resource-server. 但是,除非自定义OpaqueTokenIntrospector,则资源服务器将回退到 NimbusOpaqueTokenIntrospector。这意味着spring-security-oauth2-resource-serveroauth2-oidc-sdk对于拥有支持不透明持有Tokens的工作最小资源服务器是必要的。请参阅spring-security-oauth2-resource-server为了确定 的正确版本oauth2-oidc-sdk.spring-doc.cadn.net.cn

内省的最小配置

通常,可以通过授权服务器托管的 OAuth 2.0 Introspection Endpoint 验证不透明Tokens。当需要撤销时,这会很方便。spring-doc.cadn.net.cn

使用 Spring Boot 时,将应用程序配置为使用自省的资源服务器包括两个基本步骤。首先,包括所需的依赖项,其次,指示自省端点详细信息。spring-doc.cadn.net.cn

指定授权服务器

要指定自省终结点的位置,只需执行以下作:spring-doc.cadn.net.cn

spring:
  security:
    oauth2:
      resourceserver:
        opaque-token:
          introspection-uri: https://idp.example.com/introspect
          client-id: client
          client-secret: secret

哪里idp.example.com/introspect是由授权服务器托管的自检端点,并且client-idclient-secret是到达该终结点所需的凭据。spring-doc.cadn.net.cn

资源服务器将使用这些属性进一步自我配置并随后验证传入的 JWT。spring-doc.cadn.net.cn

使用自省时,授权服务器的词就是法律。如果授权服务器响应Tokens有效,那么它就是有效的。

就是这样!spring-doc.cadn.net.cn

创业期望

使用此属性和这些依赖项时,资源服务器将自动配置自身以验证不透明持有者Tokens。spring-doc.cadn.net.cn

这个启动过程比 JWT 简单得多,因为不需要发现端点,也不需要添加额外的验证规则。spring-doc.cadn.net.cn

运行时预期

应用程序启动后,资源服务器将尝试处理包含Authorization: Bearer页眉:spring-doc.cadn.net.cn

GET / HTTP/1.1
Authorization: Bearer some-token-value # Resource Server will process this

只要指示此方案,资源服务器就会尝试根据持有者Tokens规范处理请求。spring-doc.cadn.net.cn

给定一个不透明Tokens,资源服务器将spring-doc.cadn.net.cn

  1. 使用提供的凭据和Tokens查询提供的自检终结点spring-doc.cadn.net.cn

  2. 检查响应中的{ 'active' : true }属性spring-doc.cadn.net.cn

  3. 将每个作用域映射到具有前缀SCOPE_spring-doc.cadn.net.cn

由此产生的Authentication#getPrincipal,默认情况下是 Spring SecurityOAuth2AuthenticatedPrincipal对象,以及Authentication#getName映射到Tokens的sub属性,如果存在的话。spring-doc.cadn.net.cn

从这里,您可能想要跳转到:spring-doc.cadn.net.cn

不透明Tokens身份验证的工作原理

接下来,让我们看看 Spring Security 用于在基于 servlet 的应用程序中支持不透明Tokens身份验证的架构组件,就像我们刚刚看到的那个一样。spring-doc.cadn.net.cn

让我们来看看如何OpaqueTokenAuthenticationProvider在 Spring Security 中工作。该图解释了如何AuthenticationManager《阅读不记名Tokens》作品中的数字中。spring-doc.cadn.net.cn

opaquetokenauthentication提供程序
图 1.OpaqueTokenAuthenticationProvider用法

1号身份验证Filter读取不记名Tokens传递一个BearerTokenAuthenticationTokenAuthenticationManagerProviderManager.spring-doc.cadn.net.cn

2号ProviderManager配置为使用 AuthenticationProvider 类型OpaqueTokenAuthenticationProvider.spring-doc.cadn.net.cn

3号 OpaqueTokenAuthenticationProvider内省不透明Tokens,并使用OpaqueTokenIntrospector. 身份验证成功后,Authentication返回的 is 类型为BearerTokenAuthentication并且有一个主体,即OAuth2AuthenticatedPrincipal由配置的OpaqueTokenIntrospector. 最终,返回的BearerTokenAuthentication将设置在SecurityContextHolder通过身份验证Filter.spring-doc.cadn.net.cn

在身份验证后查找属性

Tokens经过身份验证后,实例BearerTokenAuthenticationSecurityContext.spring-doc.cadn.net.cn

这意味着它可以在@Controller使用时的方法@EnableWebMvc在您的配置中:spring-doc.cadn.net.cn

@GetMapping("/foo")
public String foo(BearerTokenAuthentication authentication) {
    return authentication.getTokenAttributes().get("sub") + " is the subject";
}
@GetMapping("/foo")
fun foo(authentication: BearerTokenAuthentication): String {
    return authentication.tokenAttributes["sub"].toString() + " is the subject"
}

因为BearerTokenAuthentication持有OAuth2AuthenticatedPrincipal,这也意味着它也可用于控制器方法:spring-doc.cadn.net.cn

@GetMapping("/foo")
public String foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
    return principal.getAttribute("sub") + " is the subject";
}
@GetMapping("/foo")
fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): String {
    return principal.getAttribute<Any>("sub").toString() + " is the subject"
}

通过 SpEL 查找属性

当然,这也意味着可以通过 SpEL 访问属性。spring-doc.cadn.net.cn

例如,如果使用@EnableGlobalMethodSecurity这样您就可以使用@PreAuthorize注释,您可以执行以下作:spring-doc.cadn.net.cn

@PreAuthorize("principal?.attributes['sub'] == 'foo'")
public String forFoosEyesOnly() {
    return "foo";
}
@PreAuthorize("principal?.attributes['sub'] == 'foo'")
fun forFoosEyesOnly(): String {
    return "foo"
}

覆盖或替换引导自动配置

有两个@BeanSpring Boot 代表资源服务器生成的。spring-doc.cadn.net.cn

第一个是SecurityFilterChain将应用配置为资源服务器。 使用不透明Tokens时,此SecurityFilterChain看来:spring-doc.cadn.net.cn

默认不透明Tokens配置
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
    return http.build();
}
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
    http {
        authorizeRequests {
            authorize(anyRequest, authenticated)
        }
        oauth2ResourceServer {
            opaqueToken { }
        }
    }
    return http.build()
}

如果应用程序未公开SecurityFilterChainbean,那么 Spring Boot 将公开上述默认的。spring-doc.cadn.net.cn

替换它就像在应用程序中公开 bean 一样简单:spring-doc.cadn.net.cn

自定义不透明Tokens配置
@Configuration
@EnableWebSecurity
public class MyCustomSecurityConfiguration {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/messages/**").hasAuthority("SCOPE_message:read")
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .opaqueToken(opaqueToken -> opaqueToken
                    .introspector(myIntrospector())
                )
            );
        return http.build();
    }
}
@Configuration
@EnableWebSecurity
class MyCustomSecurityConfiguration {
    @Bean
    open fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            authorizeRequests {
                authorize("/messages/**", hasAuthority("SCOPE_message:read"))
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                opaqueToken {
                    introspector = myIntrospector()
                }
            }
        }
        return http.build()
    }
}

以上要求范围message:read对于任何以/messages/.spring-doc.cadn.net.cn

方法oauth2ResourceServerDSL 还将覆盖或替换自动配置。spring-doc.cadn.net.cn

例如,第二个@BeanSpring Boot 创建的是一个OpaqueTokenIntrospector,哪个解码StringTokens转换为OAuth2AuthenticatedPrincipal:spring-doc.cadn.net.cn

@Bean
public OpaqueTokenIntrospector introspector() {
    return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
}
@Bean
fun introspector(): OpaqueTokenIntrospector {
    return NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
}

如果应用程序未公开OpaqueTokenIntrospectorbean,那么 Spring Boot 将公开上述默认的。spring-doc.cadn.net.cn

并且可以使用introspectionUri()introspectionClientCredentials()或使用introspector().spring-doc.cadn.net.cn

如果应用程序未公开OpaqueTokenAuthenticationConverterbean 的 Spring-security 将构建BearerTokenAuthentication.spring-doc.cadn.net.cn

或者,如果您根本不使用 Spring Boot,那么所有这些组件 - 过滤器链、OpaqueTokenIntrospectorOpaqueTokenAuthenticationConverter可以在 XML 中指定。spring-doc.cadn.net.cn

过滤器链的指定如下:spring-doc.cadn.net.cn

默认不透明Tokens配置
<http>
    <intercept-uri pattern="/**" access="authenticated"/>
    <oauth2-resource-server>
        <opaque-token introspector-ref="opaqueTokenIntrospector"
                authentication-converter-ref="opaqueTokenAuthenticationConverter"/>
    </oauth2-resource-server>
</http>
不透明Tokens内省器
<bean id="opaqueTokenIntrospector"
        class="org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector">
    <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.introspection_uri}"/>
    <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.client_id}"/>
    <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.client_secret}"/>
</bean>

以及OpaqueTokenAuthenticationConverter这样:spring-doc.cadn.net.cn

不透明Tokens身份验证转换器
<bean id="opaqueTokenAuthenticationConverter"
        class="com.example.CustomOpaqueTokenAuthenticationConverter"/>

introspectionUri()

授权服务器的 Introspection Uri 可以配置为配置属性,也可以在 DSL 中提供:spring-doc.cadn.net.cn

自检 URI 配置
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredIntrospectionUri {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .opaqueToken(opaqueToken -> opaqueToken
                    .introspectionUri("https://idp.example.com/introspect")
                    .introspectionClientCredentials("client", "secret")
                )
            );
        return http.build();
    }
}
@Configuration
@EnableWebSecurity
class DirectlyConfiguredIntrospectionUri {
    @Bean
    open fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                opaqueToken {
                    introspectionUri = "https://idp.example.com/introspect"
                    introspectionClientCredentials("client", "secret")
                }
            }
        }
        return http.build()
    }
}
<bean id="opaqueTokenIntrospector"
        class="org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector">
    <constructor-arg value="https://idp.example.com/introspect"/>
    <constructor-arg value="client"/>
    <constructor-arg value="secret"/>
</bean>

introspectionUri()优先于任何配置属性。spring-doc.cadn.net.cn

introspector()

introspectionUri()introspector(),这将完全替换OpaqueTokenIntrospector:spring-doc.cadn.net.cn

Introspector 配置
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredIntrospector {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .opaqueToken(opaqueToken -> opaqueToken
                    .introspector(myCustomIntrospector())
                )
            );
        return http.build();
    }
}
@Configuration
@EnableWebSecurity
class DirectlyConfiguredIntrospector {
    @Bean
    open fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                opaqueToken {
                    introspector = myCustomIntrospector()
                }
            }
        }
        return http.build()
    }
}
<http>
    <intercept-uri pattern="/**" access="authenticated"/>
    <oauth2-resource-server>
        <opaque-token introspector-ref="myCustomIntrospector"/>
    </oauth2-resource-server>
</http>

当需要更深层次的配置(如权限映射JWT 吊销请求超时)时,这很方便。spring-doc.cadn.net.cn

公开OpaqueTokenIntrospector @Bean

或者,公开OpaqueTokenIntrospector @Bean具有与introspector():spring-doc.cadn.net.cn

@Bean
public OpaqueTokenIntrospector introspector() {
    return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
}

配置授权

OAuth 2.0 Introspection 端点通常会返回一个scope属性,指示已授予的范围(或权限),例如:spring-doc.cadn.net.cn

{ …​, "scope" : "messages contacts"}spring-doc.cadn.net.cn

在这种情况下,资源服务器将尝试将这些作用域强制到已授予权限的列表中,并在每个作用域前面加上字符串“SCOPE_”。spring-doc.cadn.net.cn

这意味着,要保护范围派生自不透明Tokens的端点或方法,相应的表达式应包含以下前缀:spring-doc.cadn.net.cn

授权不透明Tokens配置
@Configuration
@EnableWebSecurity
public class MappedAuthorities {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorizeRequests -> authorizeRequests
                .requestMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
                .requestMatchers("/messages/**").hasAuthority("SCOPE_messages")
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
        return http.build();
    }
}
@Configuration
@EnableWebSecurity
class MappedAuthorities {
    @Bean
    open fun filterChain(http: HttpSecurity): SecurityFilterChain {
       http {
            authorizeRequests {
                authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
                authorize("/messages/**", hasAuthority("SCOPE_messages"))
                authorize(anyRequest, authenticated)
            }
           oauth2ResourceServer {
               opaqueToken { }
           }
        }
        return http.build()
    }
}
<http>
    <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
    <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
    <oauth2-resource-server>
        <opaque-token introspector-ref="opaqueTokenIntrospector"/>
    </oauth2-resource-server>
</http>

或者类似的方法安全性:spring-doc.cadn.net.cn

@PreAuthorize("hasAuthority('SCOPE_messages')")
public List<Message> getMessages(...) {}
@PreAuthorize("hasAuthority('SCOPE_messages')")
fun getMessages(): List<Message?> {}

手动提取权限

默认情况下,不透明Tokens支持将从自省响应中提取范围声明,并将其解析为单个GrantedAuthority实例。spring-doc.cadn.net.cn

例如,如果内省响应是:spring-doc.cadn.net.cn

{
    "active" : true,
    "scope" : "message:read message:write"
}

然后资源服务器将生成一个Authentication有两个权限,一个用于message:read另一个用于message:write.spring-doc.cadn.net.cn

当然,这可以使用自定义OpaqueTokenIntrospector查看属性集并以自己的方式进行转换:spring-doc.cadn.net.cn

public class CustomAuthoritiesOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
    private OpaqueTokenIntrospector delegate =
            new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");

    public OAuth2AuthenticatedPrincipal introspect(String token) {
        OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);
        return new DefaultOAuth2AuthenticatedPrincipal(
                principal.getName(), principal.getAttributes(), extractAuthorities(principal));
    }

    private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
        List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
        return scopes.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }
}
class CustomAuthoritiesOpaqueTokenIntrospector : OpaqueTokenIntrospector {
    private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
    override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
        val principal: OAuth2AuthenticatedPrincipal = delegate.introspect(token)
        return DefaultOAuth2AuthenticatedPrincipal(
                principal.name, principal.attributes, extractAuthorities(principal))
    }

    private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
        val scopes: List<String> = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE)
        return scopes
                .map { SimpleGrantedAuthority(it) }
    }
}

此后,只需将其公开为@Bean:spring-doc.cadn.net.cn

@Bean
public OpaqueTokenIntrospector introspector() {
    return new CustomAuthoritiesOpaqueTokenIntrospector();
}
@Bean
fun introspector(): OpaqueTokenIntrospector {
    return CustomAuthoritiesOpaqueTokenIntrospector()
}

配置超时

默认情况下,资源服务器使用连接超时和套接字超时(分别为 30 秒)来与授权服务器进行协调。spring-doc.cadn.net.cn

在某些情况下,这可能太短。 此外,它没有考虑更复杂的模式,例如退避和发现。spring-doc.cadn.net.cn

要调整资源服务器连接到授权服务器的方式,NimbusOpaqueTokenIntrospector接受RestOperations:spring-doc.cadn.net.cn

@Bean
public OpaqueTokenIntrospector introspector(RestTemplateBuilder builder, OAuth2ResourceServerProperties properties) {
    RestOperations rest = builder
            .basicAuthentication(properties.getOpaquetoken().getClientId(), properties.getOpaquetoken().getClientSecret())
            .setConnectTimeout(Duration.ofSeconds(60))
            .setReadTimeout(Duration.ofSeconds(60))
            .build();

    return new NimbusOpaqueTokenIntrospector(introspectionUri, rest);
}
@Bean
fun introspector(builder: RestTemplateBuilder, properties: OAuth2ResourceServerProperties): OpaqueTokenIntrospector? {
    val rest: RestOperations = builder
            .basicAuthentication(properties.opaquetoken.clientId, properties.opaquetoken.clientSecret)
            .setConnectTimeout(Duration.ofSeconds(60))
            .setReadTimeout(Duration.ofSeconds(60))
            .build()
    return NimbusOpaqueTokenIntrospector(introspectionUri, rest)
}

将 Introspection 与 JWT 结合使用

一个常见的问题是内省是否与 JWT 兼容。 Spring Security 的 Opaque Token 支持旨在不关心Tokens的格式——它很乐意将任何Tokens传递给提供的自省端点。spring-doc.cadn.net.cn

因此,假设您有一个要求,要求您在每个请求时与授权服务器进行检查,以防 JWT 已被撤销。spring-doc.cadn.net.cn

即使您对Tokens使用 JWT 格式,您的验证方法是自省,这意味着您需要执行以下作:spring-doc.cadn.net.cn

spring:
  security:
    oauth2:
      resourceserver:
        opaque-token:
          introspection-uri: https://idp.example.org/introspection
          client-id: client
          client-secret: secret

在这种情况下,生成的AuthenticationBearerTokenAuthentication. 对应OAuth2AuthenticatedPrincipal将是 Introspection 端点返回的任何内容。spring-doc.cadn.net.cn

但是,假设奇怪的是,自省端点仅返回Tokens是否处于活动状态。 现在怎么办?spring-doc.cadn.net.cn

在这种情况下,您可以创建自定义OpaqueTokenIntrospector仍命中终结点,但随后更新返回的主体,以将 JWT 声明作为属性:spring-doc.cadn.net.cn

public class JwtOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
    private OpaqueTokenIntrospector delegate =
            new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
    private JwtDecoder jwtDecoder = new NimbusJwtDecoder(new ParseOnlyJWTProcessor());

    public OAuth2AuthenticatedPrincipal introspect(String token) {
        OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);
        try {
            Jwt jwt = this.jwtDecoder.decode(token);
            return new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES);
        } catch (JwtException ex) {
            throw new OAuth2IntrospectionException(ex);
        }
    }

    private static class ParseOnlyJWTProcessor extends DefaultJWTProcessor<SecurityContext> {
    	JWTClaimsSet process(SignedJWT jwt, SecurityContext context)
                throws JOSEException {
            return jwt.getJWTClaimsSet();
        }
    }
}
class JwtOpaqueTokenIntrospector : OpaqueTokenIntrospector {
    private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
    private val jwtDecoder: JwtDecoder = NimbusJwtDecoder(ParseOnlyJWTProcessor())
    override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
        val principal = delegate.introspect(token)
        return try {
            val jwt: Jwt = jwtDecoder.decode(token)
            DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES)
        } catch (ex: JwtException) {
            throw OAuth2IntrospectionException(ex.message)
        }
    }

    private class ParseOnlyJWTProcessor : DefaultJWTProcessor<SecurityContext>() {
        override fun process(jwt: SignedJWT, context: SecurityContext): JWTClaimsSet {
            return jwt.jwtClaimsSet
        }
    }
}

此后,只需将其公开为@Bean:spring-doc.cadn.net.cn

@Bean
public OpaqueTokenIntrospector introspector() {
    return new JwtOpaqueTokenIntrospector();
}
@Bean
fun introspector(): OpaqueTokenIntrospector {
    return JwtOpaqueTokenIntrospector()
}

调用/userinfo端点

一般来说,资源服务器不关心底层用户,而是关心已授予的权限。spring-doc.cadn.net.cn

也就是说,有时将授权语句绑定回用户可能很有价值。spring-doc.cadn.net.cn

如果应用程序还使用spring-security-oauth2-client,已设置适当的ClientRegistrationRepository,那么这对于自定义OpaqueTokenIntrospector. 下面的实现执行了三件事:spring-doc.cadn.net.cn

public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
    private final OpaqueTokenIntrospector delegate =
            new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
    private final OAuth2UserService oauth2UserService = new DefaultOAuth2UserService();

    private final ClientRegistrationRepository repository;

    // ... constructor

    @Override
    public OAuth2AuthenticatedPrincipal introspect(String token) {
        OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token);
        Instant issuedAt = authorized.getAttribute(ISSUED_AT);
        Instant expiresAt = authorized.getAttribute(EXPIRES_AT);
        ClientRegistration clientRegistration = this.repository.findByRegistrationId("registration-id");
        OAuth2AccessToken token = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
        OAuth2UserRequest oauth2UserRequest = new OAuth2UserRequest(clientRegistration, token);
        return this.oauth2UserService.loadUser(oauth2UserRequest);
    }
}
class UserInfoOpaqueTokenIntrospector : OpaqueTokenIntrospector {
    private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
    private val oauth2UserService = DefaultOAuth2UserService()
    private val repository: ClientRegistrationRepository? = null

    // ... constructor

    override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
        val authorized = delegate.introspect(token)
        val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
        val expiresAt: Instant? = authorized.getAttribute(EXPIRES_AT)
        val clientRegistration: ClientRegistration = repository!!.findByRegistrationId("registration-id")
        val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
        val oauth2UserRequest = OAuth2UserRequest(clientRegistration, accessToken)
        return oauth2UserService.loadUser(oauth2UserRequest)
    }
}

如果您没有使用spring-security-oauth2-client,还是很简单的。 您只需调用/userinfo使用您自己的实例WebClient:spring-doc.cadn.net.cn

public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
    private final OpaqueTokenIntrospector delegate =
            new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
    private final WebClient rest = WebClient.create();

    @Override
    public OAuth2AuthenticatedPrincipal introspect(String token) {
        OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token);
        return makeUserInfoRequest(authorized);
    }
}
class UserInfoOpaqueTokenIntrospector : OpaqueTokenIntrospector {
    private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
    private val rest: WebClient = WebClient.create()

    override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
        val authorized = delegate.introspect(token)
        return makeUserInfoRequest(authorized)
    }
}

无论哪种方式,创建了您的OpaqueTokenIntrospector,您应该将其发布为@Bean要覆盖默认值:spring-doc.cadn.net.cn

@Bean
OpaqueTokenIntrospector introspector() {
    return new UserInfoOpaqueTokenIntrospector(...);
}
@Bean
fun introspector(): OpaqueTokenIntrospector {
    return UserInfoOpaqueTokenIntrospector(...)
}