use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class UserSessionInitializerTest method createSessionsInPersisterOnly.
// Create sessions in persister + infinispan, but then delete them from infinispan cache by reinitializing keycloak session factory
private UserSessionModel[] createSessionsInPersisterOnly() {
UserSessionModel[] origSessions = inComittedTransaction(session -> {
return UserSessionPersisterProviderTest.createSessions(session, realmId);
});
UserSessionModel[] res = new UserSessionModel[origSessions.length];
withRealm(realmId, (session, realm) -> {
int i = 0;
for (UserSessionModel origSession : origSessions) {
UserSessionModel userSession = session.sessions().getUserSession(realm, origSession.getId());
UserSessionModel offlineUserSession = session.sessions().createOfflineUserSession(userSession);
userSession.getAuthenticatedClientSessions().values().forEach(clientSession -> session.sessions().createOfflineClientSession(clientSession, offlineUserSession));
res[i++] = offlineUserSession;
}
return null;
});
reinitializeKeycloakSessionFactory();
return res;
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class UserSessionProviderModelTest method testExpiredClientSessions.
@Test
public void testExpiredClientSessions() {
// Suspend periodic tasks to avoid race-conditions, which may cause missing updates of lastSessionRefresh times to UserSessionPersisterProvider
TimerProvider timer = kcSession.getProvider(TimerProvider.class);
TimerProvider.TimerTaskContext timerTaskCtx = null;
if (timer != null) {
timerTaskCtx = timer.cancelTask(PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
log.info("Cancelled periodic task " + PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
InfinispanTestUtil.setTestingTimeService(kcSession);
}
try {
UserSessionModel[] origSessions = inComittedTransaction(session -> {
// create some user and client sessions
return createSessions(session, realmId);
});
AtomicReference<List<String>> clientSessionIds = new AtomicReference<>();
clientSessionIds.set(origSessions[0].getAuthenticatedClientSessions().values().stream().map(AuthenticatedClientSessionModel::getId).collect(Collectors.toList()));
inComittedTransaction(session -> {
RealmModel realm = session.realms().getRealm(realmId);
UserSessionModel userSession = session.sessions().getUserSession(realm, origSessions[0].getId());
Assert.assertEquals(origSessions[0], userSession);
AuthenticatedClientSessionModel clientSession = session.sessions().getClientSession(userSession, realm.getClientByClientId("test-app"), origSessions[0].getAuthenticatedClientSessionByClient(realm.getClientByClientId("test-app").getId()).getId(), false);
Assert.assertEquals(origSessions[0].getAuthenticatedClientSessionByClient(realm.getClientByClientId("test-app").getId()).getId(), clientSession.getId());
userSession = session.sessions().getUserSession(realm, origSessions[1].getId());
Assert.assertEquals(origSessions[1], userSession);
});
// not possible to expire client session without expiring user sessions with time offset in map storage because
// expiration in map storage takes min of (clientSessionIdleExpiration, ssoSessionIdleTimeout)
inComittedTransaction(session -> {
if (session.getProvider(UserSessionProvider.class) instanceof MapUserSessionProvider) {
RealmModel realm = session.realms().getRealm(realmId);
UserSessionModel userSession = session.sessions().getUserSession(realm, origSessions[0].getId());
userSession.getAuthenticatedClientSessions().values().stream().forEach(clientSession -> {
// expire client sessions
clientSession.setTimestamp(1);
});
} else {
Time.setOffset(1000);
}
});
inComittedTransaction(session -> {
RealmModel realm = session.realms().getRealm(realmId);
// assert the user session is still there
UserSessionModel userSession = session.sessions().getUserSession(realm, origSessions[0].getId());
Assert.assertEquals(origSessions[0], userSession);
// assert the client sessions are expired
clientSessionIds.get().forEach(clientSessionId -> {
Assert.assertNull(session.sessions().getClientSession(userSession, realm.getClientByClientId("test-app"), clientSessionId, false));
Assert.assertNull(session.sessions().getClientSession(userSession, realm.getClientByClientId("third-party"), clientSessionId, false));
});
});
} finally {
Time.setOffset(0);
kcSession.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
if (timer != null && timerTaskCtx != null) {
timer.schedule(timerTaskCtx.getRunnable(), timerTaskCtx.getIntervalMillis(), PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
InfinispanTestUtil.revertTimeService();
}
}
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class LoadPersistentSessionsCommand method doRunCommand.
@Override
protected void doRunCommand(KeycloakSession session) {
final int workersCount = getIntArg(0);
final int limit = getIntArg(1);
// int workersCount = 8;
// int limit = 64;
AtomicReference<String> lastSessionId = new AtomicReference<>("abc");
AtomicBoolean finished = new AtomicBoolean(false);
int i = 0;
while (!finished.get()) {
if (i % 16 == 0) {
log.infof("Starting iteration: %s . lastCreatedOn: %d, lastSessionId: %s", i, lastSessionId.get());
}
i = i + workersCount;
List<Thread> workers = new LinkedList<>();
MyWorker lastWorker = null;
for (int workerId = 0; workerId < workersCount; workerId++) {
lastWorker = new MyWorker(workerId, lastSessionId.get(), limit, sessionFactory);
Thread worker = new Thread(lastWorker);
workers.add(worker);
}
for (Thread worker : workers) {
worker.start();
}
for (Thread worker : workers) {
try {
worker.join();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
List<UserSessionModel> lastWorkerSessions = lastWorker.getLoadedSessions();
if (lastWorkerSessions.size() < limit) {
finished.set(true);
} else {
UserSessionModel lastSession = lastWorkerSessions.get(lastWorkerSessions.size() - 1);
lastSessionId.set(lastSession.getId());
}
}
log.info("All persistent sessions loaded successfully");
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class RealmAdminResource method deleteSession.
/**
* Remove a specific user session. Any client that has an admin url will also be told to invalidate this
* particular session.
*
* @param sessionId
*/
@Path("sessions/{session}")
@DELETE
public void deleteSession(@PathParam("session") String sessionId) {
auth.users().requireManage();
UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
if (userSession == null)
throw new NotFoundException("Sesssion not found");
AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), connection, headers, true);
adminEvent.operation(OperationType.DELETE).resource(ResourceType.USER_SESSION).resourcePath(session.getContext().getUri()).success();
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class SessionResource method logout.
/**
* Remove a specific session
*
* @param id a specific session to remove
* @return
*/
@Path("/{id}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response logout(@PathParam("id") String id) {
auth.require(AccountRoles.MANAGE_ACCOUNT);
UserSessionModel userSession = session.sessions().getUserSession(realm, id);
if (userSession != null && userSession.getUser().equals(user)) {
AuthenticationManager.backchannelLogout(session, userSession, true);
}
return Response.noContent().build();
}
Aggregations