Before migrating to Spring Boot 3, we used OAuth2RestTemplate
in one of our services, which worked excellently, especially when the response from the external service was '401 invalid_token'
. This implementation had a useful feature - OAuth2ErrorHandler
, which, in the event of receiving 401 and 'invalid_token' in the body, automatically renewed the token and retried the request with the new token. Additionally, if the response did not contain any body, it analyzed 'www-authenticate' in the header and retried the request as well.
In Spring Boot 3, OAuth2RestTemplate
is deprecated, and I can't find any equivalent. I am considering writing my own implementation of the retry mechanism for similar cases.
Is there an alternative to OAuth2RestTemplate
with a similar mechanism in the handler?
Spring Boot 3 uses Spring Security 6.x release versions. In Spring Security 6.3 (GA) and earlier, you can use WebClient
with an ExchangeFilterFunction
for both servlet and reactive applications. In Spring Security 6.4 (currently available in pre-release with 6.4.0-M4
), you can also use RestClient
with OAuth2ClientHttpRequestInterceptor
. This release will be generally available next month (November 2024).
There is not currently a direct replacement of the retry mechanism. However, access tokens that are known to be expired (or within the clock skew time window which is 60s
by default) will be automatically refreshed. Retry logic is not usually required in this case.
By default, the OAuth2AuthorizedClientManager
automatically removes invalid OAuth2AuthorizedClient
instances (for example, if refresh token becomes expired, revoked, etc.) on failure so the next request will trigger re-authorization. This is done through a RemoveAuthorizedClientOAuth2AuthorizationFailureHandler which you can read about in the reference.
If needed, you can add retry support through Spring Retry, as reported by one user here. Retry would probably only be useful for automatically triggering a re-authorization flow for the user without surfacing a 401 error. This could be surprising though, because returning a 401 allows the UI (for example, a javascript application) to display a message to the user prior to redirecting for re-authorization. If you are using grant types other than authorization_code
, your mileage may vary but please feel free to open an issue if you feel something is missing.
In summary, the retry mechanism from the legacy OAuth library is not usually needed with the new OAuth2 support in Spring Security since access token refresh is handled automatically.