Search in sources :

Example 66 with UserSessionModel

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;
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel)

Example 67 with UserSessionModel

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();
        }
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionProvider(org.keycloak.models.UserSessionProvider) MapUserSessionProvider(org.keycloak.models.map.userSession.MapUserSessionProvider) UserSessionModel(org.keycloak.models.UserSessionModel) ResetTimeOffsetEvent(org.keycloak.models.utils.ResetTimeOffsetEvent) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) MapUserSessionProvider(org.keycloak.models.map.userSession.MapUserSessionProvider) TimerProvider(org.keycloak.timer.TimerProvider) List(java.util.List) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 68 with UserSessionModel

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");
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) LinkedList(java.util.LinkedList) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 69 with UserSessionModel

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();
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE)

Example 70 with UserSessionModel

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();
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Aggregations

UserSessionModel (org.keycloak.models.UserSessionModel)133 RealmModel (org.keycloak.models.RealmModel)68 Test (org.junit.Test)53 ClientModel (org.keycloak.models.ClientModel)44 UserModel (org.keycloak.models.UserModel)43 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)38 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)29 KeycloakSession (org.keycloak.models.KeycloakSession)26 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)26 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)21 ClientSessionContext (org.keycloak.models.ClientSessionContext)20 AtomicReference (java.util.concurrent.atomic.AtomicReference)18 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)17 KeycloakModelTest (org.keycloak.testsuite.model.KeycloakModelTest)17 Response (javax.ws.rs.core.Response)15 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)14 List (java.util.List)13 CorsErrorResponseException (org.keycloak.services.CorsErrorResponseException)13 Map (java.util.Map)12 UserSessionPersisterProvider (org.keycloak.models.session.UserSessionPersisterProvider)12