Tokens on Feign calls

With spring.feign.oauth2.enabled=true, every Feign client sends an access token: Authorization: Bearer <token> of the user of the security context or, for a client_credentials registration, of the client. The OAuth2AccessTokenInterceptor gets it from the OAuth2AuthorizedClientManager at each call, so it is refreshed when it expires within a minute.

Why

The Feign clients of an app should call the API as the logged-in user, and a server's clients should call other services with its own token, without any code in the clients. One property switches it on; the token handling (refresh, expiry, a revoked token) stays in one place.

Example

spring.security.oauth2.client.registration.partner.client-id=shop
spring.security.oauth2.client.registration.partner.client-secret=${PARTNER_SECRET}
spring.security.oauth2.client.registration.partner.authorization-grant-type=client_credentials
spring.security.oauth2.client.provider.partner.token-uri=https://id.partner.example/oauth2/token

spring.feign.oauth2.enabled=true
spring.feign.oauth2.client-registration-id=partner
@FeignClient('orders', url: r'${partner.url}')
abstract interface class OrdersClient {
  @GetMapping('/orders')
  Future<List<Order>> orders(); // Authorization: Bearer <token>
}

Properties

Key Type Default Meaning
spring.feign.oauth2.enabled bool false Whether Feign clients send the access token of an OAuth2 client registration.
spring.feign.oauth2.client-registration-id String none: the Feign client's name The registration whose token Feign clients send.

Spring Cloud's spring.cloud.openfeign.oauth2.* names stop the start and name these.

How it works

When the API answers 401

When the API answers 401 to a token that looked valid (revoked, the provider's keys rotated), the OAuth2AccessTokenErrorDecoder marks it expired, so the next call refreshes it. The failed call itself is not repeated: Feign's interceptors do not see responses, and its ErrorDecoder and Retryer belong to the application.

The starter declares this decoder only when the application has no ErrorDecoder. Wrap yours to keep the behaviour:

@Bean()
ErrorDecoder errorDecoder(OAuth2AccessTokenInterceptor tokens) =>
    OAuth2AccessTokenErrorDecoder(MyErrorDecoder(), tokens);

With DPoP, the decoder also remembers the DPoP-Nonce of an error answer per server for the next proofs, and a 401 that only asks for a nonce leaves the token alone.

Logs

Feign's headers log masks the Authorization and DPoP headers. Nothing in the starter logs a token.

In Spring (Java)

spring.cloud.openfeign.oauth2.enabled: true
spring.cloud.openfeign.oauth2.clientRegistrationId: partner

The same behaviour as Spring Cloud OpenFeign's OAuth2AccessTokenInterceptor, under spring.feign.oauth2. The 401 error decoder and DPoP are additions. A call answered use_dpop_nonce is not repeated yet.

See also