OAuth 2.0 Bearer Tokens

Bearer Token Resolution

默认情况下,资源服务器在 Authorization 头中寻找承载令牌。然而,这可以用几种方式自定义。

Reading the Bearer Token from a Custom Header

例如,你或许有需要从自定义头中读取承载令牌。要实现这一点,你可以公开一个 DefaultBearerTokenResolver 作为 bean,或者将一个实例连接到 DSL 中,正如你在以下示例中看到的那样:

Custom Bearer Token Header
  • 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

Reading the Bearer Token from a Form Parameter

或者,您可能希望从表单参数中读取令牌,您可以通过将配置为 DefaultBearerTokenResolver 来实现,如下所示:

Form Parameter Bearer Token
  • 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 Token Propagation

现在既然你的资源服务器已经验证了令牌,那么将它传递给下游服务可能会很方便。这使用 {security-api-url}org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.html[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 并提取任何 {security-api-url}org/springframework/security/oauth2/core/AbstractOAuth2Token.html[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()

将调用 https://other-service.example.com/endpoint,为您添加 bearer token 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 过滤器链。

与 {security-api-url}org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.html[OAuth 2.0客户端过滤器函数] 不同,此过滤器函数不会尝试在令牌过期时对其进行续订。要获得此级别的支持,请使用 OAuth 2.0 客户端过滤器。

RestTemplate support

目前 RestTemplate 没有 ServletBearerExchangeFilterFunction 的等效项,但您可以用您自己的拦截器简单地传播请求的 bearer token:

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

与 {security-api-url}org/springframework/security/oauth2/client/OAuth2AuthorizedClientManager.html[OAuth 2.0 授权客户端管理器] 不同,此过滤器拦截器不会尝试在令牌过期时对其进行续订。要获得此级别的支持,请使用 OAuth 2.0 Authorized Client Manager 创建一个拦截器。

Bearer Token Failure

bearer token 可能因多种原因而无效。例如,令牌可能不再处于活动状态。

在此情况下,资源服务器会抛出一个 InvalidBearerTokenException。像其他异常一样,这会导致 OAuth 2.0 Bearer Token 错误响应:

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,您可以像这样 listen for in your application

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