OAuth 2.0 Bearer 令牌
Bearer 令牌解析
默认情况下,资源服务器在`Authorization`头中查找 Bearer 令牌。但是,这可以通过多种方式进行自定义。
从自定义头中读取 Bearer 令牌
例如,您可能需要从自定义头中读取 Bearer 令牌。为此,您可以将`DefaultBearerTokenResolver`作为 Bean 公开,或者将其实例连接到 DSL,如下例所示
-
Java
-
Kotlin
-
Xml
@Bean
BearerTokenResolver bearerTokenResolver() {
DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
bearerTokenResolver.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION);
return bearerTokenResolver;
}
@Bean
fun bearerTokenResolver(): BearerTokenResolver {
val bearerTokenResolver = DefaultBearerTokenResolver()
bearerTokenResolver.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION)
return bearerTokenResolver
}
<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`。
从表单参数中读取 Bearer 令牌
或者,您可能希望从表单参数中读取令牌,您可以通过配置`DefaultBearerTokenResolver`来实现,如下所示
-
Java
-
Kotlin
-
Xml
DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
resolver.setAllowFormEncodedBodyParameter(true);
http
.oauth2ResourceServer(oauth2 -> oauth2
.bearerTokenResolver(resolver)
);
val resolver = DefaultBearerTokenResolver()
resolver.setAllowFormEncodedBodyParameter(true)
http {
oauth2ResourceServer {
bearerTokenResolver = resolver
}
}
<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>
Bearer 令牌传播
现在您的资源服务器已经验证了令牌,将其传递给下游服务可能很有用。使用`ServletBearerExchangeFilterFunction`非常简单,您可以在下面的示例中看到
-
Java
-
Kotlin
@Bean
public WebClient rest() {
return WebClient.builder()
.filter(new ServletBearerExchangeFilterFunction())
.build();
}
@Bean
fun rest(): WebClient {
return WebClient.builder()
.filter(ServletBearerExchangeFilterFunction())
.build()
}
当使用上述`WebClient`执行请求时,Spring Security 将查找当前的`Authentication`并提取任何`AbstractOAuth2Token`凭据。然后,它将在`Authorization`头中传播该令牌。
例如
-
Java
-
Kotlin
this.rest.get()
.uri("https://other-service.example.com/endpoint")
.retrieve()
.bodyToMono(String.class)
.block()
this.rest.get()
.uri("https://other-service.example.com/endpoint")
.retrieve()
.bodyToMono<String>()
.block()
将调用`other-service.example.com/endpoint`,为您添加 Bearer 令牌`Authorization`头。
在需要覆盖此行为的地方,只需自己提供标头即可,如下所示
-
Java
-
Kotlin
this.rest.get()
.uri("https://other-service.example.com/endpoint")
.headers(headers -> headers.setBearerAuth(overridingToken))
.retrieve()
.bodyToMono(String.class)
.block()
this.rest.get()
.uri("https://other-service.example.com/endpoint")
.headers{ headers -> headers.setBearerAuth(overridingToken)}
.retrieve()
.bodyToMono<String>()
.block()
在这种情况下,过滤器将回退并简单地将请求转发到 Web 过滤器链的其余部分。
与OAuth 2.0客户端过滤器函数不同,此过滤器函数不会尝试更新令牌(如果令牌已过期)。要获得此级别的支持,请使用OAuth 2.0客户端过滤器。 |
RestTemplate
支持
目前没有RestTemplate
等效于 ServletBearerExchangeFilterFunction
的内容,但是您可以使用您自己的拦截器轻松地传播请求的令牌。
-
Java
-
Kotlin
@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;
}
@Bean
fun rest(): RestTemplate {
val rest = RestTemplate()
rest.interceptors.add(ClientHttpRequestInterceptor { request, body, execution ->
val authentication: Authentication? = SecurityContextHolder.getContext().authentication
if (authentication == null) {
return execution.execute(request, body)
}
if (authentication.credentials !is AbstractOAuth2Token) {
return execution.execute(request, body)
}
request.headers.setBearerAuth(authentication.credentials.tokenValue)
execution.execute(request, body)
})
return rest
}
与OAuth 2.0授权客户端管理器不同,此过滤器拦截器不会尝试更新令牌(如果令牌已过期)。要获得此级别的支持,请使用OAuth 2.0授权客户端管理器创建一个拦截器。 |
Bearer令牌失败
Bearer令牌可能由于多种原因无效。例如,令牌可能不再有效。
在这种情况下,资源服务器会抛出InvalidBearerTokenException
异常。与其他异常一样,这会导致OAuth 2.0 Bearer令牌错误响应。
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
事件,您可以像这样在您的应用程序中监听它
-
Java
-
Kotlin
@Component
public class FailureEvents {
@EventListener
public void onFailure(AuthenticationFailureBadCredentialsEvent badCredentials) {
if (badCredentials.getAuthentication() instanceof BearerTokenAuthenticationToken) {
// ... handle
}
}
}
@Component
class FailureEvents {
@EventListener
fun onFailure(badCredentials: AuthenticationFailureBadCredentialsEvent) {
if (badCredentials.authentication is BearerTokenAuthenticationToken) {
// ... handle
}
}
}