use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class OfflineTokenTest method browserOfflineTokenLogoutFollowedByLoginSameSession.
@Test
public void browserOfflineTokenLogoutFollowedByLoginSameSession() throws Exception {
oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
oauth.clientId("offline-client");
oauth.redirectUri(offlineClientAppUri);
oauth.doLogin("test-user@localhost", "password");
EventRepresentation loginEvent = events.expectLogin().client("offline-client").detail(Details.REDIRECT_URI, offlineClientAppUri).assertEvent();
final String sessionId = loginEvent.getSessionId();
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "secret1");
oauth.verifyToken(tokenResponse.getAccessToken());
String offlineTokenString = tokenResponse.getRefreshToken();
RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString);
events.expectCodeToToken(codeId, sessionId).client("offline-client").detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE).assertEvent();
assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineToken.getType());
assertEquals(0, offlineToken.getExpiration());
String offlineUserSessionId = testingClient.server().fetch((KeycloakSession session) -> session.sessions().getOfflineUserSession(session.realms().getRealmByName("test"), offlineToken.getSessionState()).getId(), String.class);
// logout offline session
try (CloseableHttpResponse logoutResponse = oauth.doLogout(offlineTokenString, "secret1")) {
assertEquals(204, logoutResponse.getStatusLine().getStatusCode());
}
events.expectLogout(offlineUserSessionId).client("offline-client").removeDetail(Details.REDIRECT_URI).assertEvent();
// Need to login again now
oauth.doLogin("test-user@localhost", "password");
String code2 = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
OAuthClient.AccessTokenResponse tokenResponse2 = oauth.doAccessTokenRequest(code2, "secret1");
assertEquals(200, tokenResponse2.getStatusCode());
oauth.verifyToken(tokenResponse2.getAccessToken());
String offlineTokenString2 = tokenResponse2.getRefreshToken();
RefreshToken offlineToken2 = oauth.parseRefreshToken(offlineTokenString2);
loginEvent = events.expectLogin().client("offline-client").detail(Details.REDIRECT_URI, offlineClientAppUri).assertEvent();
codeId = loginEvent.getDetails().get(Details.CODE_ID);
events.expectCodeToToken(codeId, offlineToken2.getSessionState()).client("offline-client").detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE).assertEvent();
assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineToken2.getType());
assertEquals(0, offlineToken2.getExpiration());
// Assert session changed
assertNotEquals(offlineToken.getSessionState(), offlineToken2.getSessionState());
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class InfinispanUserLoginFailureProviderFactory method postInit.
@Override
public void postInit(final KeycloakSessionFactory factory) {
this.remoteCacheInvoker = new RemoteCacheInvoker();
factory.register(event -> {
if (event instanceof PostMigrationEvent) {
KeycloakModelUtils.runJobInTransaction(factory, (KeycloakSession session) -> {
checkRemoteCaches(session);
registerClusterListeners(session);
loadLoginFailuresFromRemoteCaches(session);
});
} else if (event instanceof UserModel.UserRemovedEvent) {
UserModel.UserRemovedEvent userRemovedEvent = (UserModel.UserRemovedEvent) event;
UserLoginFailureProvider provider = userRemovedEvent.getKeycloakSession().getProvider(UserLoginFailureProvider.class, getId());
provider.removeUserLoginFailure(userRemovedEvent.getRealm(), userRemovedEvent.getUser().getId());
}
});
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class InfinispanUserSessionProviderFactory method registerClusterListeners.
protected void registerClusterListeners(KeycloakSession session) {
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
ClusterProvider cluster = session.getProvider(ClusterProvider.class);
cluster.registerListener(REALM_REMOVED_SESSION_EVENT, new AbstractUserSessionClusterListener<RealmRemovedSessionEvent, UserSessionProvider>(sessionFactory, UserSessionProvider.class) {
@Override
protected void eventReceived(KeycloakSession session, UserSessionProvider provider, RealmRemovedSessionEvent sessionEvent) {
if (provider instanceof InfinispanUserSessionProvider) {
((InfinispanUserSessionProvider) provider).onRealmRemovedEvent(sessionEvent.getRealmId());
}
}
});
cluster.registerListener(CLIENT_REMOVED_SESSION_EVENT, new AbstractUserSessionClusterListener<ClientRemovedSessionEvent, UserSessionProvider>(sessionFactory, UserSessionProvider.class) {
@Override
protected void eventReceived(KeycloakSession session, UserSessionProvider provider, ClientRemovedSessionEvent sessionEvent) {
if (provider instanceof InfinispanUserSessionProvider) {
((InfinispanUserSessionProvider) provider).onClientRemovedEvent(sessionEvent.getRealmId(), sessionEvent.getClientUuid());
}
}
});
cluster.registerListener(REMOVE_USER_SESSIONS_EVENT, new AbstractUserSessionClusterListener<RemoveUserSessionsEvent, UserSessionProvider>(sessionFactory, UserSessionProvider.class) {
@Override
protected void eventReceived(KeycloakSession session, UserSessionProvider provider, RemoveUserSessionsEvent sessionEvent) {
if (provider instanceof InfinispanUserSessionProvider) {
((InfinispanUserSessionProvider) provider).onRemoveUserSessionsEvent(sessionEvent.getRealmId());
}
}
});
log.debug("Registered cluster listeners");
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class InfinispanUserSessionProviderFactory method postInit.
@Override
public void postInit(final KeycloakSessionFactory factory) {
factory.register(new ProviderEventListener() {
@Override
public void onEvent(ProviderEvent event) {
if (event instanceof PostMigrationEvent) {
int preloadTransactionTimeout = getTimeoutForPreloadingSessionsSeconds();
log.debugf("Will preload sessions with transaction timeout %d seconds", preloadTransactionTimeout);
KeycloakModelUtils.runJobInTransactionWithTimeout(factory, (KeycloakSession session) -> {
keyGenerator = new InfinispanKeyGenerator();
checkRemoteCaches(session);
loadPersistentSessions(factory, getMaxErrors(), getSessionsPerSegment());
registerClusterListeners(session);
loadSessionsFromRemoteCaches(session);
}, preloadTransactionTimeout);
} else if (event instanceof UserModel.UserRemovedEvent) {
UserModel.UserRemovedEvent userRemovedEvent = (UserModel.UserRemovedEvent) event;
InfinispanUserSessionProvider provider = (InfinispanUserSessionProvider) userRemovedEvent.getKeycloakSession().getProvider(UserSessionProvider.class, getId());
provider.onUserRemoved(userRemovedEvent.getRealm(), userRemovedEvent.getUser());
} else if (event instanceof ResetTimeOffsetEvent) {
if (persisterLastSessionRefreshStore != null) {
persisterLastSessionRefreshStore.reset();
}
if (lastSessionRefreshStore != null) {
lastSessionRefreshStore.reset();
}
if (offlineLastSessionRefreshStore != null) {
offlineLastSessionRefreshStore.reset();
}
}
}
});
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class MultipleStepsExportProvider method exportRealmImpl.
protected void exportRealmImpl(KeycloakSessionFactory factory, final String realmName) throws IOException {
final UsersExportStrategy usersExportStrategy = ExportImportConfig.getUsersExportStrategy();
final int usersPerFile = ExportImportConfig.getUsersPerFile();
final UsersHolder usersHolder = new UsersHolder();
final boolean exportUsersIntoRealmFile = usersExportStrategy == UsersExportStrategy.REALM_FILE;
FederatedUsersHolder federatedUsersHolder = new FederatedUsersHolder();
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
protected void runExportImportTask(KeycloakSession session) throws IOException {
RealmModel realm = session.realms().getRealmByName(realmName);
RealmRepresentation rep = ExportUtils.exportRealm(session, realm, exportUsersIntoRealmFile, true);
writeRealm(realmName + "-realm.json", rep);
logger.info("Realm '" + realmName + "' - data exported");
// Count total number of users
if (!exportUsersIntoRealmFile) {
usersHolder.totalCount = session.users().getUsersCount(realm, true);
federatedUsersHolder.totalCount = session.userFederatedStorage().getStoredUsersCount(realm);
}
}
});
if (usersExportStrategy != UsersExportStrategy.SKIP && !exportUsersIntoRealmFile) {
// We need to export users now
usersHolder.currentPageStart = 0;
// usersExportStrategy==SAME_FILE means exporting all users into single file (but separate to realm)
final int countPerPage = (usersExportStrategy == UsersExportStrategy.SAME_FILE) ? usersHolder.totalCount : usersPerFile;
while (usersHolder.currentPageStart < usersHolder.totalCount) {
if (usersHolder.currentPageStart + countPerPage < usersHolder.totalCount) {
usersHolder.currentPageEnd = usersHolder.currentPageStart + countPerPage;
} else {
usersHolder.currentPageEnd = usersHolder.totalCount;
}
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
protected void runExportImportTask(KeycloakSession session) throws IOException {
RealmModel realm = session.realms().getRealmByName(realmName);
usersHolder.users = session.users().getUsersStream(realm, usersHolder.currentPageStart, usersHolder.currentPageEnd - usersHolder.currentPageStart, true).collect(Collectors.toList());
writeUsers(realmName + "-users-" + (usersHolder.currentPageStart / countPerPage) + ".json", session, realm, usersHolder.users);
logger.info("Users " + usersHolder.currentPageStart + "-" + (usersHolder.currentPageEnd - 1) + " exported");
}
});
usersHolder.currentPageStart = usersHolder.currentPageEnd;
}
}
if (usersExportStrategy != UsersExportStrategy.SKIP && !exportUsersIntoRealmFile) {
// We need to export users now
federatedUsersHolder.currentPageStart = 0;
// usersExportStrategy==SAME_FILE means exporting all users into single file (but separate to realm)
final int countPerPage = (usersExportStrategy == UsersExportStrategy.SAME_FILE) ? federatedUsersHolder.totalCount : usersPerFile;
while (federatedUsersHolder.currentPageStart < federatedUsersHolder.totalCount) {
if (federatedUsersHolder.currentPageStart + countPerPage < federatedUsersHolder.totalCount) {
federatedUsersHolder.currentPageEnd = federatedUsersHolder.currentPageStart + countPerPage;
} else {
federatedUsersHolder.currentPageEnd = federatedUsersHolder.totalCount;
}
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
protected void runExportImportTask(KeycloakSession session) throws IOException {
RealmModel realm = session.realms().getRealmByName(realmName);
federatedUsersHolder.users = session.userFederatedStorage().getStoredUsersStream(realm, federatedUsersHolder.currentPageStart, federatedUsersHolder.currentPageEnd - federatedUsersHolder.currentPageStart).collect(Collectors.toList());
writeFederatedUsers(realmName + "-federated-users-" + (federatedUsersHolder.currentPageStart / countPerPage) + ".json", session, realm, federatedUsersHolder.users);
logger.info("Users " + federatedUsersHolder.currentPageStart + "-" + (federatedUsersHolder.currentPageEnd - 1) + " exported");
}
});
federatedUsersHolder.currentPageStart = federatedUsersHolder.currentPageEnd;
}
}
}
Aggregations