How does my Spring Boot client application access a refresh token supplied by e.g. Google in Spring Security 5?
Pretty simple question. The remote authorization server (e.g. Google) sends a refresh token, and I want to use it. What's the best way to persist and retrieve it in Spring Security 5?
It seems this answer, this question, and this exernal link describe an approach no longer compatible since Oauth2 became a first-class citizen in Spring Security 5.
Context:
Refresh tokens allow a client application to continue to access resources after a user's session has expired. Per Google's docs, refresh tokens should be persistent:
The application should store the refresh token for future use and use the access token to access a Google API.
Spring security makes the access token widely available in the form of an OAuth2AuthenticationToken, but the refresh token is not included there.
The refresh token is also not available in the OidcUserService
(or a class that overrides it), since public OidcUser loadUser(OidcUserRequest userRequest)
does not have access to the refresh token. This is a bummer, since it would be nice to override OidcUserService with a custom class that creates/retrieves a user from their OIDC user details and saves their associated refresh token at the same time.
The OAuth2LoginAuthenticationFilter
saves the refresh token in the ClientRegistrationRepository:
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(),
oauth2Authentication.getName(),
authenticationResult.getAccessToken(),
authenticationResult.getRefreshToken());
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, oauth2Authentication, request, response);
The default implemetation keeps the token in transient memory, which is not suitable for distributed applications or persisting across restarts.
It seems there is a JdbcOauth2AuthorizedClientService
, with docs recently added, and a schema that suggests that it could be useful, but no example was provided either of configuring it or of using it to retrieve a refresh token.
So how can a client application persist and access refresh token in Spring Security 5?