# OAuth2.0不记名代币

## 不记名令牌解析

默认情况下，Resource Server在`Authorization`头中查找承载令牌。然而，这可以通过几种方式进行定制。

### 从自定义标头读取不记名令牌

例如，你可能需要从自定义报头读取承载令牌。为了实现这一点，你可以将`DefaultBearerTokenResolver`公开为 Bean，或者将一个实例连接到DSL中，正如你在下面的示例中所看到的那样：

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

Java

```
@Bean
BearerTokenResolver bearerTokenResolver() {
    DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
    bearerTokenResolver.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION);
    return bearerTokenResolver;
}
```

Kotlin

```
@Bean
fun bearerTokenResolver(): BearerTokenResolver {
    val bearerTokenResolver = DefaultBearerTokenResolver()
    bearerTokenResolver.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION)
    return bearerTokenResolver
}
```

XML

```
<http>
    <oauth2-resource-server bearer-token-resolver-ref="bearerTokenResolver"/>
</http>

<bean id="bearerTokenResolver"
        class="org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver">
    <property name="bearerTokenHeaderName" value="Proxy-Authorization"/>
</bean>
```

或者，在提供者同时使用自定义头和值的情况下，你可以使用`HeaderBearerTokenResolver`。

### 从窗体参数读取承载令牌

或者，你可能希望从一个表单参数读取令牌，这可以通过配置`DefaultBearerTokenResolver`来实现，如下所示：

例2.表单参数承载令牌

Java

```
DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
resolver.setAllowFormEncodedBodyParameter(true);
http
    .oauth2ResourceServer(oauth2 -> oauth2
        .bearerTokenResolver(resolver)
    );
```

Kotlin

```
val resolver = DefaultBearerTokenResolver()
resolver.setAllowFormEncodedBodyParameter(true)
http {
    oauth2ResourceServer {
        bearerTokenResolver = resolver
    }
}
```

XML

```
<http>
    <oauth2-resource-server bearer-token-resolver-ref="bearerTokenResolver"/>
</http>

<bean id="bearerTokenResolver"
        class="org.springframework.security.oauth2.server.resource.web.HeaderBearerTokenResolver">
    <property name="allowFormEncodedBodyParameter" value="true"/>
</bean>
```

## 承载令牌传播

既然你的资源服务器已经验证了令牌，那么将其传递给下游服务可能会很方便。对于`[ServletBearerExchangeFilterFunction](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.html)`，这非常简单，你可以在下面的示例中看到它：

Java

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

Kotlin

```
@Bean
fun rest(): WebClient {
    return WebClient.builder()
            .filter(ServletBearerExchangeFilterFunction())
            .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`头中传播该令牌。

例如：

Java

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

Kotlin

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

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

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

Java

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

Kotlin

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

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

|   |与[OAuth2.0客户端过滤功能](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.html)不同，如果令牌过期，此筛选函数不尝试更新令牌。<br/>要获得此级别的支持，请使用OAuth2.0客户端筛选。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### `RestTemplate`支持

目前还没有`RestTemplate`的`ServletBearerExchangeFilterFunction`等价物，但是你可以使用自己的拦截器非常简单地传播请求的承载令牌：

Java

```
@Bean
RestTemplate rest() {
	RestTemplate rest = new RestTemplate();
	rest.getInterceptors().add((request, body, execution) -> {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return execution.execute(request, body);
		}

		if (!(authentication.getCredentials() instanceof AbstractOAuth2Token)) {
			return execution.execute(request, body);
		}

		AbstractOAuth2Token token = (AbstractOAuth2Token) authentication.getCredentials();
	    request.getHeaders().setBearerAuth(token.getTokenValue());
	    return execution.execute(request, body);
	});
	return rest;
}
```

Kotlin

```
@Bean
fun rest(): RestTemplate {
    val rest = RestTemplate()
    rest.interceptors.add(ClientHttpRequestInterceptor { request, body, execution ->
        val authentication: Authentication? = SecurityContextHolder.getContext().authentication
        if (authentication != null) {
            execution.execute(request, body)
        }

        if (authentication!!.credentials !is AbstractOAuth2Token) {
            execution.execute(request, body)
        }

        val token: AbstractOAuth2Token = authentication.credentials as AbstractOAuth2Token
        request.headers.setBearerAuth(token.tokenValue)
        execution.execute(request, body)
    })
    return rest
}
```

|   |与[OAuth2.0授权客户经理](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/client/OAuth2AuthorizedClientManager.html)不同的是，如果令牌过期，这个过滤器拦截器不会尝试更新令牌。<br/>要获得这种级别的支持，请使用[OAuth2.0授权客户经理](../client/index.html#oauth2client)创建一个拦截器。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

## 承载令牌失败

不记名令牌可能由于多种原因而无效。例如，令牌可能不再是活动的。

在这种情况下，资源服务器抛出一个`InvalidBearerTokenException`。与其他异常一样，这会导致一个OAuth2.0承载令牌错误响应：

```
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error_code="invalid_token", error_description="Unsupported algorithm of none", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
```

此外，它以`AuthenticationFailureBadCredentialsEvent`的形式发布，你可以像这样[在你的应用程序中监听](../../authentication/events.html#servlet-events):

Java

```
@Component
public class FailureEvents {
	@EventListener
    public void onFailure(AuthenticationFailureBadCredentialsEvent badCredentials) {
		if (badCredentials.getAuthentication() instanceof BearerTokenAuthenticationToken) {
		    // ... handle
        }
    }
}
```

Kotlin

```
@Component
class FailureEvents {
    @EventListener
    fun onFailure(badCredentials: AuthenticationFailureBadCredentialsEvent) {
        if (badCredentials.authentication is BearerTokenAuthenticationToken) {
            // ... handle
        }
    }
}
```

[多租约](multitenancy.html)[SAML2](../../saml2/index.html)