OAuth 2.0 資源伺服器不透明令牌

內省的最小依賴

JWT 的最小依賴 中所述,大多數資源伺服器支援集中在 spring-security-oauth2-resource-server 中。然而,除非你提供自定義的 ReactiveOpaqueTokenIntrospector,否則資源伺服器會回退到 ReactiveOpaqueTokenIntrospector。這意味著 spring-security-oauth2-resource-serveroauth2-oidc-sdk 都必需,才能有一個支援不透明 Bearer 令牌的最小工作資源伺服器。請查閱 spring-security-oauth2-resource-server 以確定 oauth2-oidc-sdk 的正確版本。

內省的最小配置

通常,你可以使用授權伺服器託管的 OAuth 2.0 內省端點 (OAuth 2.0 Introspection Endpoint) 來驗證不透明令牌。當需要令牌撤銷時,這會很方便。

使用 Spring Boot 時,將應用程式配置為使用內省的資源伺服器需要兩個步驟:

  1. 包含所需的依賴。

  2. 指定內省端點詳情。

指定授權伺服器

你可以指定內省端點的位置:

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 是訪問該端點所需的憑據。

資源伺服器使用這些屬性進行進一步的自我配置,並隨後驗證傳入的 JWT。

如果授權伺服器響應表明令牌有效,那麼它就是有效的。

啟動時的預期行為

當使用此屬性和這些依賴時,資源伺服器會自動配置自身以驗證不透明的 Bearer 令牌。

這個啟動過程比 JWT 要簡單得多,因為不需要發現端點,也不會新增額外的驗證規則。

執行時預期行為

應用程式啟動後,資源伺服器會嘗試處理任何包含 Authorization: Bearer 頭資訊的請求:

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

只要指定了這種方案,資源伺服器就會嘗試根據 Bearer 令牌規範處理請求。

給定一個不透明令牌,資源伺服器會:

  1. 使用提供的憑據和令牌查詢提供的內省端點。

  2. 檢查響應中是否存在 { 'active' : true } 屬性。

  3. 將每個 scope 對映到一個以 SCOPE_ 為字首的許可權 (authority)。

預設情況下,生成的 Authentication#getPrincipal 是一個 Spring Security OAuth2AuthenticatedPrincipal 物件,並且 Authentication#getName 對映到令牌的 sub 屬性(如果存在的話)。

接下來,你可能想跳到:

認證後查詢屬性

令牌認證成功後,一個 BearerTokenAuthentication 例項會被設定到 SecurityContext 中。

這意味著當你在配置中使用 @EnableWebFlux 時,它可以在 @Controller 方法中使用:

  • 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,這也意味著它也可以在 controller 方法中使用:

  • 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")
}

使用 SpEL 查詢屬性

你可以使用 Spring 表示式語言 (SpEL) 訪問屬性。

例如,如果你使用 @EnableReactiveMethodSecurity 以便可以使用 @PreAuthorize 註解,你可以這樣做:

  • 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")
}

覆蓋或替換 Boot 自動配置

Spring Boot 為資源伺服器生成兩個 @Bean 例項。

第一個是 SecurityWebFilterChain,它將應用程式配置為資源伺服器。當你使用不透明令牌時,這個 SecurityWebFilterChain 看起來像這樣:

  • 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(如前面列表中所示)。

你可以透過在應用程式中暴露該 bean 來替換它:

替換 SecurityWebFilterChain
  • 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()
            }
        }
    }
}

前面的示例要求任何以 /messages/ 開頭的 URL 都具有 message:read 的 scope。

oauth2ResourceServer DSL 中的方法也可以覆蓋或替換自動配置。

例如,Spring Boot 建立的第二個 @BeanReactiveOpaqueTokenIntrospector,它將 String 令牌解碼為經過驗證的 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 會暴露預設的(如前面列表中所示)。

你可以透過使用 introspectionUri()introspectionClientCredentials() 來覆蓋其配置,或透過使用 introspector() 來完全替換它。

使用 introspectionUri()

你可以將授權伺服器的內省 URI 配置為一個配置屬性,或者在 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() 優先於任何配置屬性。

使用 introspector()

introspector()introspectionUri() 更強大。它完全替換了 Boot 對 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()
            }
        }
    }
}

當需要更深層的配置(例如 許可權對映JWT 撤銷)時,這會很方便。

暴露一個 ReactiveOpaqueTokenIntrospector@Bean

或者,暴露一個 ReactiveOpaqueTokenIntrospector@Beanintrospector() 具有相同的效果:

  • Java

  • Kotlin

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

配置授權

OAuth 2.0 內省端點通常返回一個 scope 屬性,指示已授予的 scope(或許可權)——例如:

{ ..., "scope" : "messages contacts"}

在這種情況下,資源伺服器會嘗試將這些 scope 轉換為已授予許可權的列表,併為每個 scope 新增字首字串:SCOPE_

這意味著,要使用源自不透明令牌的 scope 保護端點或方法時,相應的表示式應包含此字首:

  • 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 { }
        }
    }
}

你也可以使用方法安全做類似的事情:

  • Java

  • Kotlin

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

手動提取許可權

預設情況下,不透明令牌支援從內省響應中提取 scope claim 並將其解析為單個 GrantedAuthority 例項。

考慮以下示例:

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

如果內省響應如前面的示例所示,資源伺服器將生成一個包含兩個許可權的 Authentication,一個用於 message:read,另一個用於 message:write

你可以透過使用自定義的 ReactiveOpaqueTokenIntrospector 來定製行為,該 introspector 會檢視屬性集並以自己的方式進行轉換:

  • 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) }
    }
}

之後,你可以透過將其暴露為 @Bean 來配置此自定義 introspector:

  • Java

  • Kotlin

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

將內省與 JWT 結合使用

一個常見的問題是內省是否與 JWT 相容。Spring Security 的不透明令牌支援被設計成不關心令牌的格式。它會樂意將任何令牌傳遞給提供的內省端點。

所以,假設你需要在每個請求中都向授權伺服器檢查,以防 JWT 已被撤銷。

即使你使用 JWT 格式的令牌,你的驗證方法是內省,這意味著你將希望這樣做:

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

在這種情況下,生成的 Authentication 將是 BearerTokenAuthentication。相應的 OAuth2AuthenticatedPrincipal 中的任何屬性都將是內省端點返回的內容。

然而,假設出於某種原因,內省端點只返回令牌是否啟用。現在該怎麼辦?

在這種情況下,你可以建立一個自定義的 ReactiveOpaqueTokenIntrospector,它仍然會訪問該端點,但隨後更新返回的 principal,將 JWT 的 claims 作為屬性:

  • 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)
            }
        }
    }
}

之後,你可以透過將其暴露為 @Bean 來配置此自定義 introspector:

  • Java

  • Kotlin

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

呼叫 /userinfo 端點

一般來說,資源伺服器不關心底層使用者,而是關心已被授予的許可權。

話雖如此,有時將授權宣告與使用者關聯起來會很有價值。

如果應用程式還使用了 spring-security-oauth2-client,並且設定了適當的 ClientRegistrationRepository,你可以使用自定義的 OpaqueTokenIntrospector 來實現這一點。下一個列表中的實現做了三件事:

  • 委託給內省端點,以確認令牌的有效性。

  • 查詢與 /userinfo 端點關聯的相應客戶端註冊。

  • 呼叫並返回來自 /userinfo 端點的響應。

  • 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 端點:

  • 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 以覆蓋預設配置:

  • Java

  • Kotlin

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