OAuth 2.0 Resource Server Opaque Token
Minimal Dependencies for Introspection
正如在 Minimal Dependencies for JWT 中所述,大多数 Resource Server 支持都在 spring-security-oauth2-resource-server
中收集。但是,除非您提供自定义的 <<`ReactiveOpaqueTokenIntrospector`,webflux-oauth2resourceserver-opaque-introspector-bean>>,否则 Resource Server 会回退到 ReactiveOpaqueTokenIntrospector
。这意味着同时需要 spring-security-oauth2-resource-server
和 oauth2-oidc-sdk
才能拥有支持不透明 Bearer 令牌的基本的正常工作的 Resource Server。请参阅 spring-security-oauth2-resource-server
以确定 oauth2-oidc-sdk
的正确版本。
As described in Minimal Dependencies for JWT, most Resource Server support is collected in spring-security-oauth2-resource-server
.
However, unless you provide a custom <<`ReactiveOpaqueTokenIntrospector`,webflux-oauth2resourceserver-opaque-introspector-bean>>, the Resource Server falls back to ReactiveOpaqueTokenIntrospector
.
This means that both spring-security-oauth2-resource-server
and oauth2-oidc-sdk
are necessary to have a working minimal Resource Server that supports opaque Bearer Tokens.
See spring-security-oauth2-resource-server
in order to determine the correct version for oauth2-oidc-sdk
.
Minimal Configuration for Introspection
通常,你可以在由授权服务器托管的 OAuth 2.0 Introspection Endpoint 中验证不透明令牌。当撤销是一个要求时,这会很方便。
Typically, you can verify an opaque token with an OAuth 2.0 Introspection Endpoint, hosted by the authorization server. This can be handy when revocation is a requirement.
在使用 Spring Boot 时,将应用程序配置为使用内省的资源服务器包括两个步骤:
When using Spring Boot, configuring an application as a resource server that uses introspection consists of two steps:
-
Include the needed dependencies.
-
Indicate the introspection endpoint details.
Specifying the Authorization Server
你可以指定内省端点在哪里:
You can specify where the introspection endpoint is:
spring:
security:
oauth2:
resourceserver:
opaque-token:
introspection-uri: https://idp.example.com/introspect
client-id: client
client-secret: secret
其中 https://idp.example.com/introspect
是授权服务器托管的省察端点,client-id
和 client-secret
是访问该端点所需的凭据。
Where https://idp.example.com/introspect
is the introspection endpoint hosted by your authorization server and client-id
and client-secret
are the credentials needed to hit that endpoint.
Resource Server 使用这些属性进一步自配置,并随后验证传入的 JWT。
Resource Server uses these properties to further self-configure and subsequently validate incoming JWTs.
如果授权服务器响应令牌有效,那么它就是有效的。 If the authorization server responses that the token is valid, then it is. |
Startup Expectations
当此属性和这些依赖关系被使用时,Resource Server 会自动配置自身以验证不透明承载令牌。
When this property and these dependencies are used, Resource Server automatically configures itself to validate Opaque Bearer Tokens.
这个启动过程比 JWT 简单很多,因为不需要发现端点,且不会添加任何额外验证规则。
This startup process is quite a bit simpler than for JWTs, since no endpoints need to be discovered and no additional validation rules get added.
Runtime Expectations
一旦应用程序启动,资源服务器将尝试处理任何包含 Authorization: Bearer
标头的请求:
Once the application has started, Resource Server tries to process any request containing an Authorization: Bearer
header:
GET / HTTP/1.1
Authorization: Bearer some-token-value # Resource Server will process this
只要指示此方案,资源服务器就会尝试根据 Bearer 令牌规范处理请求。
So long as this scheme is indicated, Resource Server tries to process the request according to the Bearer Token specification.
给定不透明令牌,Resource Server:
Given an Opaque Token, Resource Server:
-
Queries the provided introspection endpoint by using the provided credentials and the token.
-
Inspects the response for an
{ 'active' : true }
attribute. -
Maps each scope to an authority with a prefix of
SCOPE_
.
默认情况下,产生的 Authentication#getPrincipal
是一个 Spring Security {security-api-url}org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html[OAuth2AuthenticatedPrincipal]
对象,如果存在,Authentication#getName
映射到令牌的 sub
属性。
By default, the resulting Authentication#getPrincipal
is a Spring Security {security-api-url}org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html[OAuth2AuthenticatedPrincipal]
object, and Authentication#getName
maps to the token’s sub
property, if one is present.
从这里,您可能希望跳转到:
From here, you may want to jump to:
Looking Up Attributes After Authentication
令牌通过认证后,BearerTokenAuthentication
实例将设置在 SecurityContext
中。
Once a token is authenticated, an instance of BearerTokenAuthentication
is set in the SecurityContext
.
这意味着当你在配置中使用 @EnableWebFlux
时,它可在 @Controller
方法中获取:
This means that it is available in @Controller
methods when you use @EnableWebFlux
in your configuration:
-
Java
-
Kotlin
@GetMapping("/foo")
public Mono<String> foo(BearerTokenAuthentication authentication) {
return Mono.just(authentication.getTokenAttributes().get("sub") + " is the subject");
}
@GetMapping("/foo")
fun foo(authentication: BearerTokenAuthentication): Mono<String> {
return Mono.just(authentication.tokenAttributes["sub"].toString() + " is the subject")
}
由于 BearerTokenAuthentication
持有 OAuth2AuthenticatedPrincipal
,这意味着它也可以在控制器方法中使用:
Since BearerTokenAuthentication
holds an OAuth2AuthenticatedPrincipal
, that also means that it’s available to controller methods, too:
-
Java
-
Kotlin
@GetMapping("/foo")
public Mono<String> foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
return Mono.just(principal.getAttribute("sub") + " is the subject");
}
@GetMapping("/foo")
fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): Mono<String> {
return Mono.just(principal.getAttribute<Any>("sub").toString() + " is the subject")
}
Looking Up Attributes with SpEL
你可以使用 Spring 表达式语言 (SpEL) 来访问属性。
You can access attributes with the Spring Expression Language (SpEL).
例如,如果您使用 @EnableReactiveMethodSecurity
,这样就可以使用 `@PreAuthorize`批注,可以执行:
For example, if you use @EnableReactiveMethodSecurity
so that you can use @PreAuthorize
annotations, you can do:
-
Java
-
Kotlin
@PreAuthorize("principal?.attributes['sub'] = 'foo'")
public Mono<String> forFoosEyesOnly() {
return Mono.just("foo");
}
@PreAuthorize("principal.attributes['sub'] = 'foo'")
fun forFoosEyesOnly(): Mono<String> {
return Mono.just("foo")
}
Overriding or Replacing Boot Auto Configuration
Spring Boot 为资源服务器生成了两个 `@Bean`实例。
Spring Boot generates two @Bean
instances for Resource Server.
第一个是 SecurityWebFilterChain
,将应用程序配置为资源服务器。当您使用不透明令牌时,`SecurityWebFilterChain`类似:
The first is a SecurityWebFilterChain
that configures the application as a resource server.
When you use an Opaque Token, this SecurityWebFilterChain
looks like:
-
Java
-
Kotlin
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.anyExchange().authenticated()
)
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken)
return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
oauth2ResourceServer {
opaqueToken { }
}
}
}
如果应用程序不公开 `SecurityWebFilterChain`Bean,Spring Boot 会公开默认 Bean(在上一个清单中展示)。
If the application does not expose a SecurityWebFilterChain
bean, Spring Boot exposes the default bean (shown in the preceding listing).
你可以通过在应用程序中公开 bean 来替换它:
You can replace it by exposing the bean within the application:
-
Java
-
Kotlin
import static org.springframework.security.oauth2.core.authorization.OAuth2ReactiveAuthorizationManagers.hasScope;
@Configuration
@EnableWebFluxSecurity
public class MyCustomSecurityConfiguration {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.pathMatchers("/messages/**").access(hasScope("message:read"))
.anyExchange().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.opaqueToken(opaqueToken -> opaqueToken
.introspector(myIntrospector())
)
);
return http.build();
}
}
import org.springframework.security.oauth2.core.authorization.OAuth2ReactiveAuthorizationManagers.hasScope
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize("/messages/**", hasScope("message:read"))
authorize(anyExchange, authenticated)
}
oauth2ResourceServer {
opaqueToken {
introspector = myIntrospector()
}
}
}
}
以上示例需要 message:read
的范围用于以 /messages/
开头的任何 URL。
The preceding example requires the scope of message:read
for any URL that starts with /messages/
.
oauth2ResourceServer
DSL 上的方法也会覆盖或替换自动配置。
Methods on the oauth2ResourceServer
DSL also override or replace auto configuration.
例如,第二个 @Bean
创建的 Spring Boot 是 ReactiveOpaqueTokenIntrospector
,它将 String
令牌解码成 OAuth2AuthenticatedPrincipal
的验证实例:
For example, the second @Bean
Spring Boot creates is a ReactiveOpaqueTokenIntrospector
, which decodes String
tokens into validated instances of OAuth2AuthenticatedPrincipal
:
-
Java
-
Kotlin
@Bean
public ReactiveOpaqueTokenIntrospector introspector() {
return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
}
@Bean
fun introspector(): ReactiveOpaqueTokenIntrospector {
return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
}
如果应用程序没有公开 ReactiveOpaqueTokenIntrospector
bean,Spring Boot 将公开默认的 bean(如上一个列表中所示)。
If the application does not expose a ReactiveOpaqueTokenIntrospector
bean, Spring Boot exposes the default one (shown in the preceding listing).
你可以使用 introspectionUri()
和 introspectionClientCredentials()
覆盖其配置,或者使用 introspector()
替换它。
You can override its configuration by using introspectionUri()
and introspectionClientCredentials()
or replace it by using introspector()
.
Using introspectionUri()
你可以配置授权服务器的 Introspection URI as a configuration property,也可以在 DSL 中提供:
You can configure an authorization server’s Introspection URI webflux-oauth2resourceserver-opaque-introspectionuri, or you can supply in the DSL:
-
Java
-
Kotlin
@Configuration
@EnableWebFluxSecurity
public class DirectlyConfiguredIntrospectionUri {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.anyExchange().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.opaqueToken(opaqueToken -> opaqueToken
.introspectionUri("https://idp.example.com/introspect")
.introspectionClientCredentials("client", "secret")
)
);
return http.build();
}
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
oauth2ResourceServer {
opaqueToken {
introspectionUri = "https://idp.example.com/introspect"
introspectionClientCredentials("client", "secret")
}
}
}
}
使用 introspectionUri()
优先于任何配置属性。
Using introspectionUri()
takes precedence over any configuration property.
Using introspector()
introspector()
比 introspectionUri()
更加强大。它完全替换所有 ReactiveOpaqueTokenIntrospector
的 Boot 自动配置:
introspector()
is more powerful than introspectionUri()
. It completely replaces any Boot auto-configuration of ReactiveOpaqueTokenIntrospector
:
-
Java
-
Kotlin
@Configuration
@EnableWebFluxSecurity
public class DirectlyConfiguredIntrospector {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.anyExchange().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.opaqueToken(opaqueToken -> opaqueToken
.introspector(myCustomIntrospector())
)
);
return http.build();
}
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
oauth2ResourceServer {
opaqueToken {
introspector = myCustomIntrospector()
}
}
}
}
这在需要更深入的配置(例如 authority mapping 或 JWT revocation)时非常方便。
This is handy when deeper configuration, such as webflux-oauth2resourceserver-opaque-authorization-extractionor webflux-oauth2resourceserver-opaque-jwt-introspector, is necessary.
Exposing a ReactiveOpaqueTokenIntrospector
@Bean
或者,公开 ReactiveOpaqueTokenIntrospector
@Bean
与 introspector()
具有相同的效果:
Or, exposing a ReactiveOpaqueTokenIntrospector
@Bean
has the same effect as introspector()
:
-
Java
-
Kotlin
@Bean
public ReactiveOpaqueTokenIntrospector introspector() {
return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
}
@Bean
fun introspector(): ReactiveOpaqueTokenIntrospector {
return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
}
Configuring Authorization
OAuth2.0 Introspection 端点通常返回 scope
属性,指示已授予的范围(或权限)——例如:
An OAuth 2.0 Introspection endpoint typically returns a scope
attribute, indicating the scopes (or authorities) it has been granted — for example:
{ ..., "scope" : "messages contacts"}
在这种情况下,资源服务器尝试将这些范围强制为授予权限的列表,并在每个范围前加上字符串:SCOPE_
。
When this is the case, Resource Server tries to coerce these scopes into a list of granted authorities, prefixing each scope with a string: SCOPE_
.
这意味着,要使用不透明令牌派生的范围来保护端点或方法,对应的表达式应该包含此前缀:
This means that, to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
-
Java
-
Kotlin
import static org.springframework.security.oauth2.core.authorization.OAuth2ReactiveAuthorizationManagers.hasScope;
@Configuration
@EnableWebFluxSecurity
public class MappedAuthorities {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchange -> exchange
.pathMatchers("/contacts/**").access(hasScope("contacts"))
.pathMatchers("/messages/**").access(hasScope("messages"))
.anyExchange().authenticated()
)
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken);
return http.build();
}
}
import org.springframework.security.oauth2.core.authorization.OAuth2ReactiveAuthorizationManagers.hasScope
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize("/contacts/**", hasScope("contacts"))
authorize("/messages/**", hasScope("messages"))
authorize(anyExchange, authenticated)
}
oauth2ResourceServer {
opaqueToken { }
}
}
}
你可以对方法安全执行类似操作:
You can do something similar with method security:
-
Java
-
Kotlin
@PreAuthorize("hasAuthority('SCOPE_messages')")
public Flux<Message> getMessages(...) {}
@PreAuthorize("hasAuthority('SCOPE_messages')")
fun getMessages(): Flux<Message> { }
Extracting Authorities Manually
默认情况下,不透明令牌支持从 introspection 响应中提取范围声明,并将其解析为单独的 GrantedAuthority
实例。
By default, Opaque Token support extracts the scope claim from an introspection response and parses it into individual GrantedAuthority
instances.
请考虑以下示例:
Consider the following example:
{
"active" : true,
"scope" : "message:read message:write"
}
如果 introspection 响应如前一个示例所示,资源服务器将生成一个 Authentication
,它具有两个权限,一个用于 message:read
,另一个用于 message:write
。
If the introspection response were as the preceding example shows, Resource Server would generate an Authentication
with two authorities, one for message:read
and the other for message:write
.
你可以使用查看属性集并以其自己的方式转换的自定义 ReactiveOpaqueTokenIntrospector
来定制行为:
You can customize behavior by using a custom ReactiveOpaqueTokenIntrospector
that looks at the attribute set and converts in its own way:
-
Java
-
Kotlin
public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
private ReactiveOpaqueTokenIntrospector delegate =
new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
return this.delegate.introspect(token)
.map(principal -> 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 : ReactiveOpaqueTokenIntrospector {
private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
return delegate.introspect(token)
.map { principal: OAuth2AuthenticatedPrincipal ->
DefaultOAuth2AuthenticatedPrincipal(
principal.name, principal.attributes, extractAuthorities(principal))
}
}
private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
val scopes = principal.getAttribute<List<String>>(OAuth2IntrospectionClaimNames.SCOPE)
return scopes
.map { SimpleGrantedAuthority(it) }
}
}
此后,你可以通过将该自定义 introspector 公开为 @Bean
来配置它:
Thereafter, you can configure this custom introspector by exposing it as a @Bean
:
-
Java
-
Kotlin
@Bean
public ReactiveOpaqueTokenIntrospector introspector() {
return new CustomAuthoritiesOpaqueTokenIntrospector();
}
@Bean
fun introspector(): ReactiveOpaqueTokenIntrospector {
return CustomAuthoritiesOpaqueTokenIntrospector()
}
Using Introspection with JWTs
一个常见问题是 introspection 是否与 JWT 兼容。Spring Security 的不透明令牌支持被设计为不关心令牌的格式。它将愉快地将任何令牌传递给提供的 introspection 端点。
A common question is whether or not introspection is compatible with JWTs. Spring Security’s Opaque Token support has been designed to not care about the format of the token. It gladly passes any token to the provided introspection endpoint.
因此,假设你需要在每个请求上向授权服务器进行检查,以防 JWT 被吊销。
So, suppose you need to check with the authorization server on each request, in case the JWT has been revoked.
即使你对令牌使用 JWT 格式,你的验证方法也是 introspection,这意味着你想要执行以下操作:
Even though you are using the JWT format for the token, your validation method is introspection, meaning you would want to do:
spring:
security:
oauth2:
resourceserver:
opaque-token:
introspection-uri: https://idp.example.org/introspection
client-id: client
client-secret: secret
在这种情况下,结果的 Authentication
是 BearerTokenAuthentication
。相应 OAuth2AuthenticatedPrincipal
中的任何属性都将是不透明身份验证端点返回的任何内容。
In this case, the resulting Authentication
would be BearerTokenAuthentication
.
Any attributes in the corresponding OAuth2AuthenticatedPrincipal
would be whatever was returned by the introspection endpoint.
但是,假设由于某种原因,introspection 端点仅返回令牌是否处于活动状态。现在该怎么办?
However, suppose that, for whatever reason, the introspection endpoint returns only whether or not the token is active. Now what?
在这种情况下,你可以创建一个自定义 ReactiveOpaqueTokenIntrospector
,它仍然会命中端点,然后更新返回的主体以将 JWT 的声明作为属性:
In this case, you can create a custom ReactiveOpaqueTokenIntrospector
that still hits the endpoint but then updates the returned principal to have the JWTs claims as the attributes:
-
Java
-
Kotlin
public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
private ReactiveOpaqueTokenIntrospector delegate =
new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
private ReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder(new ParseOnlyJWTProcessor());
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
return this.delegate.introspect(token)
.flatMap(principal -> this.jwtDecoder.decode(token))
.map(jwt -> new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES));
}
private static class ParseOnlyJWTProcessor implements Converter<JWT, Mono<JWTClaimsSet>> {
public Mono<JWTClaimsSet> convert(JWT jwt) {
try {
return Mono.just(jwt.getJWTClaimsSet());
} catch (Exception ex) {
return Mono.error(ex);
}
}
}
}
class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
private val jwtDecoder: ReactiveJwtDecoder = NimbusReactiveJwtDecoder(ParseOnlyJWTProcessor())
override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
return delegate.introspect(token)
.flatMap { jwtDecoder.decode(token) }
.map { jwt: Jwt -> DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES) }
}
private class ParseOnlyJWTProcessor : Converter<JWT, Mono<JWTClaimsSet>> {
override fun convert(jwt: JWT): Mono<JWTClaimsSet> {
return try {
Mono.just(jwt.jwtClaimsSet)
} catch (e: Exception) {
Mono.error(e)
}
}
}
}
此后,你可以通过将该自定义 introspector 公开为 @Bean
来配置它:
Thereafter, you can configure this custom introspector by exposing it as a @Bean
:
-
Java
-
Kotlin
@Bean
public ReactiveOpaqueTokenIntrospector introspector() {
return new JwtOpaqueTokenIntropsector();
}
@Bean
fun introspector(): ReactiveOpaqueTokenIntrospector {
return JwtOpaqueTokenIntrospector()
}
Calling a /userinfo
Endpoint
总体来说,一个资源服务器不关注基础用户,而是关注授予的权限。
Generally speaking, a Resource Server does not care about the underlying user but, instead, cares about the authorities that have been granted.
也就是说,有时将授权声明重新关联到用户身上可能是有价值的。
That said, at times it can be valuable to tie the authorization statement back to a user.
如果一个应用程序还使用 spring-security-oauth2-client
,设置了合适的 ClientRegistrationRepository
,您可以通过一个自定义 OpaqueTokenIntrospector
来实现。在接下来列表中的实现做了三件事:
If an application also uses spring-security-oauth2-client
, having set up the appropriate ClientRegistrationRepository
, you can do so with a custom OpaqueTokenIntrospector
.
The implementation in the next listing does three things:
-
Delegates to the introspection endpoint, to affirm the token’s validity.
-
Looks up the appropriate client registration associated with the
/userinfo
endpoint. -
Invokes and returns the response from the
/userinfo
endpoint.
-
Java
-
Kotlin
public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
private final ReactiveOpaqueTokenIntrospector delegate =
new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService =
new DefaultReactiveOAuth2UserService();
private final ReactiveClientRegistrationRepository repository;
// ... constructor
@Override
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
return Mono.zip(this.delegate.introspect(token), this.repository.findByRegistrationId("registration-id"))
.map(t -> {
OAuth2AuthenticatedPrincipal authorized = t.getT1();
ClientRegistration clientRegistration = t.getT2();
Instant issuedAt = authorized.getAttribute(ISSUED_AT);
Instant expiresAt = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
OAuth2AccessToken accessToken = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
return new OAuth2UserRequest(clientRegistration, accessToken);
})
.flatMap(this.oauth2UserService::loadUser);
}
}
class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
private val oauth2UserService: ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> = DefaultReactiveOAuth2UserService()
private val repository: ReactiveClientRegistrationRepository? = null
// ... constructor
override fun introspect(token: String?): Mono<OAuth2AuthenticatedPrincipal> {
return Mono.zip<OAuth2AuthenticatedPrincipal, ClientRegistration>(delegate.introspect(token), repository!!.findByRegistrationId("registration-id"))
.map<OAuth2UserRequest> { t: Tuple2<OAuth2AuthenticatedPrincipal, ClientRegistration> ->
val authorized = t.t1
val clientRegistration = t.t2
val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
val expiresAt: Instant? = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT)
val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
OAuth2UserRequest(clientRegistration, accessToken)
}
.flatMap { userRequest: OAuth2UserRequest -> oauth2UserService.loadUser(userRequest) }
}
}
如果你没有使用 spring-security-oauth2-client
,操作起来还是非常简单。你只需使用你自己的 WebClient
实例调用 /userinfo
:
If you aren’t using spring-security-oauth2-client
, it’s still quite simple.
You will simply need to invoke the /userinfo
with your own instance of WebClient
:
-
Java
-
Kotlin
public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
private final ReactiveOpaqueTokenIntrospector delegate =
new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
private final WebClient rest = WebClient.create();
@Override
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
return this.delegate.introspect(token)
.map(this::makeUserInfoRequest);
}
}
class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
private val rest: WebClient = WebClient.create()
override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
return delegate.introspect(token)
.map(this::makeUserInfoRequest)
}
}
无论哪种方式,创建 ReactiveOpaqueTokenIntrospector
后,您都应该将其作为 @Bean
发布,以覆盖默认值:
Either way, having created your ReactiveOpaqueTokenIntrospector
, you should publish it as a @Bean
to override the defaults:
-
Java
-
Kotlin
@Bean
ReactiveOpaqueTokenIntrospector introspector() {
return new UserInfoOpaqueTokenIntrospector();
}
@Bean
fun introspector(): ReactiveOpaqueTokenIntrospector {
return UserInfoOpaqueTokenIntrospector()
}