OAuth 2.0 授权码令牌
授权码令牌解析
默认情况下,资源服务器会在 Authorization
标头中查找授权码令牌。但是,可以通过多种方式自定义此行为。
从自定义标头读取授权码令牌
例如,您可能需要从自定义标头读取授权码令牌。要实现此目的,您可以将 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
。
从表单参数读取授权码令牌
或者,您可能希望从表单参数读取令牌,您可以通过配置 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>
授权码令牌传播
现在您的资源服务器已经验证了令牌,将其传递给下游服务可能很方便。使用 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
,并为您添加授权码令牌 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 授权客户端管理器 创建一个拦截器。 |
承载令牌失败
承载令牌可能由于多种原因无效。例如,令牌可能不再处于活动状态。
在这种情况下,资源服务器会抛出 InvalidBearerTokenException
。与其他异常一样,这会导致 OAuth 2.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
发布,您可以 在您的应用程序中监听它,如下所示
-
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
}
}
}