fix: refresh expired stored token in exchangeStoredToken (#49341) [fk4WqyCCw3C5ShR1RfB7MoBPTpkRrBFYP1uT35g3MvT] - #51358
Open
waterWang wants to merge 1 commit into
Conversation
) Backport the token refresh logic from retrieveToken (V1) to exchangeStoredToken (used by V2 and token exchange paths). When the stored access token has expired and a refresh token is available, exchangeStoredToken now automatically refreshes the token before returning it, matching the behavior of the V1 retrieveToken method. Closes keycloak#49341 [fk4WqyCCw3C5ShR1RfB7MoBPTpkRrBFYP1uT35g3MvT]
Contributor
There was a problem hiding this comment.
Pull request overview
Adds stored OAuth2 token refresh handling to the base identity provider.
Changes:
- Detects expired stored tokens and refreshes them.
- Persists and returns the refreshed access token.
- Preserves fallback handling for non-JSON tokens.
Suppressed comments (2)
services/src/main/java/org/keycloak/broker/oidc/AbstractOAuth2IdentityProvider.java:519
- Add coverage for an expired stored JSON token through a non-OIDC
AbstractOAuth2IdentityProvidersubclass, asserting refresh, persistence, and the returned fresh token. Existing broker refresh coverage exercises the OIDC override, so it cannot catch regressions in this new base-class branch.
model.setToken(JsonSerialization.writeValueAsString(newResponse));
session.users().updateFederatedIdentity(realm, tokenSubject, model);
AccessTokenResponse tokenResponse = new AccessTokenResponse();
tokenResponse.setToken(newResponse.getToken());
return buildTokenResponse(uriInfo, event, authorizedClient, tokenUserSession, tokenResponse, OAuth2Constants.ACCESS_TOKEN_TYPE);
services/src/main/java/org/keycloak/broker/oidc/AbstractOAuth2IdentityProvider.java:524
- Do not swallow refresh I/O/deserialization failures and then fall through:
modelstill contains the expired token, so lines 526–539 return that stale token as a successful response. Match the existing V1 behavior by returning a gateway error instead.
} catch (IOException e) {
logger.debugf("Failed to refresh stored token", e);
}
Comment on lines
+509
to
+510
| if (needsRefresh(exp) && previousResponse.getRefreshToken() != null) { | ||
| OAuthResponse newResponse = refreshToken(previousResponse, session); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The
exchangeStoredTokenmethod inAbstractOAuth2IdentityProvider(used by the V2/broker/{alias}/tokenendpoint and the token exchange path) returns the stored access token without checking whether it has expired. When the token is expired, the caller receives a stale token that will fail when used.The V1
retrieveTokenmethod already handles this correctly: it checksaccessTokenExpiration, and if the token needs refresh and a refresh token is available, it callsrefreshTokenand updates the stored token.Changes
This PR backports the same token refresh logic to
exchangeStoredToken:OAuthResponse(the same class used by V1retrieveToken)needsRefresh()(expired or withinminValidityToken)refreshToken()to obtain a new tokenaccessTokenExpirationon the new responseupdateFederatedIdentityIf the token is not JSON (e.g., form-encoded), the original
extractTokenFromResponsefallback path is preserved.Related
exchangeStoredToken(V2 and token exchange paths) was not updated at that timeOIDCIdentityProvideralready had its own override ofexchangeStoredTokenwith refresh logic; this change brings the same behavior to the base class, benefiting all OAuth2-based identity providers (GitHub, Facebook, Google, etc.)