# OAuth2.0 资源服务器承载令牌

# 不记名令牌解析

默认情况下,Resource Server 在Authorization头中查找承载令牌。然而,这是可以定制的。

例如,你可能需要从自定义报头读取承载令牌。为了实现这一点,你可以将ServerBearerTokenAuthenticationConverter的一个实例连接到 DSL 中,正如你在下面的示例中所看到的那样:

例 1。自定义承载令牌标头

爪哇

ServerBearerTokenAuthenticationConverter converter = new ServerBearerTokenAuthenticationConverter();
converter.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION);
http
    .oauth2ResourceServer(oauth2 -> oauth2
        .bearerTokenConverter(converter)
    );

Kotlin

val converter = ServerBearerTokenAuthenticationConverter()
converter.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION)
return http {
    oauth2ResourceServer {
        bearerTokenConverter = converter
    }
}

# 承载令牌传播

既然你已经拥有了一个无记名令牌,那么将其传递给下游服务可能会很方便。这对[ServerBearerExchangeFilterFunction](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.html)来说非常简单,你可以在下面的示例中看到这一点:

爪哇

@Bean
public WebClient rest() {
    return WebClient.builder()
            .filter(new ServerBearerExchangeFilterFunction())
            .build();
}

Kotlin

@Bean
fun rest(): WebClient {
    return WebClient.builder()
            .filter(ServerBearerExchangeFilterFunction())
            .build()
}

当上面的WebClient用于执行请求时, Spring Security 将查找当前的Authentication并提取任何[AbstractOAuth2Token](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/core/AbstractOAuth2Token.html)凭据。然后,它将在Authorization头中传播该令牌。

例如:

爪哇

this.rest.get()
        .uri("https://other-service.example.com/endpoint")
        .retrieve()
        .bodyToMono(String.class)

Kotlin

this.rest.get()
        .uri("https://other-service.example.com/endpoint")
        .retrieve()
        .bodyToMono<String>()

将调用[https://other-service.example.com/endpoint](https://other-service.example.com/endpoint),为你添加承载令牌Authorization头。

在需要重写此行为的地方,你只需自己提供标题,就像这样:

爪哇

this.rest.get()
        .uri("https://other-service.example.com/endpoint")
        .headers(headers -> headers.setBearerAuth(overridingToken))
        .retrieve()
        .bodyToMono(String.class)

Kotlin

rest.get()
        .uri("https://other-service.example.com/endpoint")
        .headers { it.setBearerAuth(overridingToken) }
        .retrieve()
        .bodyToMono<String>()

在这种情况下,过滤器将向后退,只需将请求转发到 Web 筛选链的其余部分。

OAuth2.0 客户端过滤功能 (opens new window)不同,如果令牌过期,此筛选函数不尝试更新令牌。
要获得此级别的支持,请使用 OAuth2.0 客户端筛选。

多租约保护免受剥削