Skip to content

Commit

Permalink
25815 do not remove previous refresh token for federated identity
Browse files Browse the repository at this point in the history
Signed-off-by: Geoffrey Fourmis <geoffrey.fourmis@gmail.com>
  • Loading branch information
geoffreyfourmis authored and pedroigor committed Mar 7, 2024
1 parent 4038506 commit 21f5bea
Showing 1 changed file with 24 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
import org.keycloak.protocol.saml.SamlSessionUtils;
import org.keycloak.protocol.saml.preprocessor.SamlAuthenticationPreprocessor;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.services.ErrorPage;
import org.keycloak.services.ErrorPageException;
import org.keycloak.services.ErrorResponse;
Expand Down Expand Up @@ -1048,12 +1049,31 @@ private void migrateFederatedIdentityId(BrokeredIdentityContext context, UserMod

private void updateToken(BrokeredIdentityContext context, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) {
if (context.getIdpConfig().isStoreToken() && !ObjectUtil.isEqualOrBothNull(context.getToken(), federatedIdentityModel.getToken())) {
federatedIdentityModel.setToken(context.getToken());
try {
// like in OIDCIdentityProvider.exchangeStoredToken()
// we shouldn't override the refresh token if it is null in the context and not null in the DB
// as for google IDP it will be lost forever
if (federatedIdentityModel.getToken() != null) {
AccessTokenResponse previousResponse = JsonSerialization.readValue(federatedIdentityModel.getToken(), AccessTokenResponse.class);
AccessTokenResponse newResponse = JsonSerialization.readValue(context.getToken(), AccessTokenResponse.class);

if (newResponse.getRefreshToken() == null && previousResponse.getRefreshToken() != null) {
newResponse.setRefreshToken(previousResponse.getRefreshToken());
newResponse.setRefreshExpiresIn(previousResponse.getRefreshExpiresIn());
}

this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, federatedIdentityModel);
federatedIdentityModel.setToken(JsonSerialization.writeValueAsString(newResponse));
} else {
federatedIdentityModel.setToken(context.getToken());
}

if (isDebugEnabled()) {
logger.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, context.getIdpConfig().getAlias());
this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, federatedIdentityModel);

if (isDebugEnabled()) {
logger.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, context.getIdpConfig().getAlias());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Expand Down

0 comments on commit 21f5bea

Please sign in to comment.