8000 [26.8] Reject online refresh tokens for sessions in logout states by lhanusov · Pull Request #55046 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ The client application is responsible for persisting the offline token in storag

The difference between a refresh token and an offline token is that an offline token never expires and is not subject to the `SSO Session Idle` timeout and `SSO Session Max` lifespan. The offline token is valid after a user logout. You must use the offline token for a refresh token action at least once per thirty days or for the value of the <<_offline-session-idle, Offline Session Idle>>.

Online refresh tokens cannot be used once logout begins for the user session or the associated client session, even if a front-channel logout flow has not finished. Offline tokens are unaffected by this restriction.

If you enable <<_offline-session-max-limited, Offline Session Max Limited>>, offline tokens expire after 60 days even if you use the offline token for a refresh token action. You can change this value, <<_offline-session-max, Offline Session Max>>, in the Admin Console.

When using offline access, client idle and max timeouts can be overridden at the <<_client_advanced_settings_oidc,client level>>. The options *Client Offline Session Idle* and *Client Offline Session Max*, in the client *Advanced Settings* tab, allow you to have a shorter offline timeouts for a specific application. Note that client session values also control the refresh token expiration but they never affect the global offline user SSO session. The option *Client Offline Session Max* is only evaluated in the client if <<_offline-session-max-limited, Offline Session Max Limited>> is *Enabled* at the realm level.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@
import org.keycloak.services.util.MtlsHoKTokenUtil;
import org.keycloak.services.util.UserSessionUtil;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.sessions.CommonClientSessionModel;
import org.keycloak.tracing.TracingAttributes;
import org.keycloak.tracing.TracingProvider;
import org.keycloak.util.JWKSUtils;
Expand Down Expand Up @@ -204,6 +205,12 @@ public TokenValidation validateToken(KeycloakSession session, UriInfo uriInfo, C
} else {
// Find userSession regularly for online tokens
userSession = session.sessions().getUserSession(realm, oldToken.getSessionState());
// Non-browser grants can leave the state unset; logout always sets an explicit state.
UserSessionModel.State state = userSession == null ? null : userSession.getState();
// Reject separately from expiration cleanup so front-channel logout can still finish.
if (state != null && state != UserSessionModel.State.LOGGED_IN) {
throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Session not active", "Session not active");
}
if (!AuthenticationManager.isSessionValid(realm, userSession)) {
if (userSession != null) {
UserSessionModel >
Expand Down Expand Up @@ -241,6 +248,11 @@ public TokenValidation validateToken(KeycloakSession session, UriInfo uriInfo, C
throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Session doesn't have required client", "Session doesn't have required client");
}

if (!offline && (CommonClientSessionModel.Action.LOGGING_OUT.name().equals(clientSession.getAction())
|| CommonClientSessionModel.Action.LOGGED_OUT.name().equals(clientSession.getAction()))) {
throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Client session not active");
}

if (!AuthenticationManager.isClientSessionValid(realm, client, userSession, clientSession)) {
logger.debug("Client session not active");
UserSessionModel currentSession = userSession;
Expand Down
< 6236 /tr>
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.jose.jws.crypto.HashUtils;
import org.keycloak.models.AccountRoles;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.Constants;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.sessions.infinispan.InfinispanUserSessionProviderFactory;
import org.keycloak.models.utils.KeycloakModelUtils;
Expand All @@ -60,6 +62,7 @@
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.sessions.CommonClientSessionModel;
import org.keycloak.testframework.annotations.InjectAdminClient;
import org.keycloak.testframework.annotations.InjectEvents;
import org.keycloak.testframework.annotations.InjectRealm;
Expand Down Expand Up @@ -101,6 +104,8 @@
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.openqa.selenium.Cookie;

import static org.keycloak.connections.infinispan.InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME;
Expand All @@ -112,7 +117,10 @@
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
Expand Down Expand Up @@ -185,6 +193,71 @@ public static void enableRefreshTokenEvents(ManagedRealm realm) {
}
}

@ParameterizedTest
@EnumSource(value = UserSessionModel.State.class, names = "LOGGED_IN", mode = EnumSource.Mode.EXCLUDE)
public void rejectRefreshAfterUserLogoutBegins(UserSessionModel.State state) {
assertRefreshRejected(state, null, "Session not active");
}

@ParameterizedTest
@EnumSource(value = CommonClientSessionModel.Action.class, names = {"LOGGING_OUT", "LOGGED_OUT"})
public void rejectRefreshAfterClientLogoutBegins(CommonClientSessionModel.Action action) {
assertRefreshRejected(UserSessionModel.State.LOGGED_IN, action.name(), "Client session not active");
}

private void assertRefreshRejected(UserSessionModel.State state, String action, String errorDescription) {
AccessTokenResponse tokens = loginForRefreshToken();
String sessionId = oauth.parseRefreshToken(tokens.getRefreshToken()).getSessionId();
int[] timestamps = runOnServer.fetch(session -> {
UserSessionModel userSession = session.sessions().getUserSession(session.getContext().getRealm(), sessionId);
userSession.setState(state);
AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessions().values().iterator().next();
clientSession.setAction(action);
return new int[] { userSession.getLastSessionRefresh(), clientSession.getTimestamp() };
}, int[].class);

timeOffSet.set(10);
AccessTokenResponse response = oauth.doRefreshTokenRequest(tokens.getRefreshToken());
assertThat(response.getStatusCode(), is(400));
assertThat(response.getError(), is(OAuthErrorException.INVALID_GRANT));
assertThat(response.getErrorDescription(), is(errorDescription));
assertThat(response.getAccessToken(), nullValue());
assertThat(response.getRefreshToken(), nullValue());

// A rejected refresh must neither extend idle validity nor remove state needed to complete SLO.
runOnServer.run(session -> {
UserSessionModel userSession = session.sessions().getUserSession(session.getContext().getRealm(), sessionId);
assertThat(userSession, notNullValue());
assertThat(userSession.getState(), is(state));
assertThat(userSession.getLastSessionRefresh(), is(timestamps[0]));
AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessions().values().iterator().next();
assertThat(clientSession.getAction(), is(action));
assertThat(clientSession.getTimestamp(), is(timestamps[1]));
});
}

@Test
public void offlineRefreshAfterLogout() {
try {
oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
AccessTokenResponse tokens = loginForRefreshToken();
user.admin().logout();

AccessTokenResponse response = oauth.doRefreshTokenRequest(tokens.getRefreshToken());
assertThat(response.getStatusCode(), is(200));
assertThat(response.getAccessToken(), notNullValue());
assertThat(response.getRefreshToken(), notNullValue());
} finally {
oauth.scope(null);
}
}

private AccessTokenResponse loginForRefreshToken() {
AccessTokenResponse response = oauth.doPasswordGrantRequest(user.getUsername(), user.getPassword());
assertThat(response.getStatusCode(), is(200));
return response;
}

/**
* KEYCLOAK-547
*
Expand Down
Loading
0