Search in sources :

Example 6 with UserSessionManager

use of org.keycloak.services.managers.UserSessionManager in project keycloak by keycloak.

the class UserSessionProviderOfflineTest method testOnRealmRemoved.

@Test
@ModelTest
public void testOnRealmRemoved(KeycloakSession session) {
    AtomicReference<String> userSessionID = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR1) -> {
        currentSession = sessionRR1;
        RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
        fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
        fooRealm.setSsoSessionIdleTimeout(1800);
        fooRealm.setSsoSessionMaxLifespan(36000);
        fooRealm.setOfflineSessionIdleTimeout(2592000);
        fooRealm.setOfflineSessionMaxLifespan(5184000);
        fooRealm.addClient("foo-app");
        currentSession.users().addUser(fooRealm, "user3");
        UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
        userSessionID.set(userSession.getId());
        createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR2) -> {
        currentSession = sessionRR2;
        sessionManager = new UserSessionManager(currentSession);
        // Persist offline session
        RealmModel fooRealm = currentSession.realms().getRealm("foo");
        UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
        createOfflineSessionIncludeClientSessions(currentSession, userSession);
        UserSessionModel offlineUserSession = sessionManager.findOfflineUserSession(fooRealm, userSession.getId());
        Assert.assertEquals(offlineUserSession.getAuthenticatedClientSessions().size(), 1);
        AuthenticatedClientSessionModel offlineClientSession = offlineUserSession.getAuthenticatedClientSessions().values().iterator().next();
        Assert.assertEquals("foo-app", offlineClientSession.getClient().getClientId());
        Assert.assertEquals("user3", offlineClientSession.getUserSession().getUser().getUsername());
        // Remove realm
        RealmManager realmMgr = new RealmManager(currentSession);
        realmMgr.removeRealm(realmMgr.getRealm("foo"));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR3) -> {
        currentSession = sessionRR3;
        RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
        fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
        fooRealm.addClient("foo-app");
        currentSession.users().addUser(fooRealm, "user3");
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR4) -> {
        currentSession = sessionRR4;
        RealmModel fooRealm = currentSession.realms().getRealm("foo");
        Assert.assertEquals(0, currentSession.sessions().getOfflineSessionsCount(fooRealm, fooRealm.getClientByClientId("foo-app")));
        // Cleanup
        RealmManager realmMgr = new RealmManager(currentSession);
        realmMgr.removeRealm(realmMgr.getRealm("foo"));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionManager(org.keycloak.services.managers.UserSessionManager) UserSessionModel(org.keycloak.models.UserSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 7 with UserSessionManager

use of org.keycloak.services.managers.UserSessionManager in project keycloak by keycloak.

the class UserSessionProviderOfflineTest method testOnClientRemoved.

@Test
@ModelTest
public void testOnClientRemoved(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR) -> {
        try {
            int started = Time.currentTime();
            AtomicReference<String> userSessionID = new AtomicReference<>();
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR1) -> {
                currentSession = sessionCR1;
                sessionManager = new UserSessionManager(currentSession);
                RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
                fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
                fooRealm.setSsoSessionIdleTimeout(1800);
                fooRealm.setSsoSessionMaxLifespan(36000);
                fooRealm.setOfflineSessionIdleTimeout(2592000);
                fooRealm.setOfflineSessionMaxLifespan(5184000);
                fooRealm.addClient("foo-app");
                fooRealm.addClient("bar-app");
                currentSession.users().addUser(fooRealm, "user3");
                UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
                userSessionID.set(userSession.getId());
                createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
                createClientSession(currentSession, fooRealm.getClientByClientId("bar-app"), userSession, "http://redirect", "state");
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR2) -> {
                currentSession = sessionCR2;
                // Create offline currentSession
                RealmModel fooRealm = currentSession.realms().getRealm("foo");
                UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
                createOfflineSessionIncludeClientSessions(currentSession, userSession);
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR3) -> {
                currentSession = sessionCR3;
                RealmManager realmMgr = new RealmManager(currentSession);
                ClientManager clientMgr = new ClientManager(realmMgr);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                // Assert currentSession was persisted with both clientSessions
                UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
                assertSession(offlineSession, currentSession.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app");
                // Remove foo-app client
                ClientModel client = fooRealm.getClientByClientId("foo-app");
                clientMgr.removeClient(fooRealm, client);
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR4) -> {
                currentSession = sessionCR4;
                RealmManager realmMgr = new RealmManager(currentSession);
                ClientManager clientMgr = new ClientManager(realmMgr);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                // Assert just one bar-app clientSession persisted now
                UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
                Assert.assertEquals(1, offlineSession.getAuthenticatedClientSessions().size());
                Assert.assertEquals("bar-app", offlineSession.getAuthenticatedClientSessions().values().iterator().next().getClient().getClientId());
                // Remove bar-app client
                ClientModel client = fooRealm.getClientByClientId("bar-app");
                clientMgr.removeClient(fooRealm, client);
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR5) -> {
                currentSession = sessionCR5;
                // Assert nothing loaded - userSession was removed as well because it was last userSession
                RealmManager realmMgr = new RealmManager(currentSession);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
                Assert.assertEquals(0, offlineSession.getAuthenticatedClientSessions().size());
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTearDown) -> {
                currentSession = sessionTearDown;
                RealmManager realmMgr = new RealmManager(currentSession);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
                // Remove user3
                new UserManager(currentSession).removeUser(fooRealm, user3);
                // Cleanup
                realmMgr = new RealmManager(currentSession);
                realmMgr.removeRealm(realmMgr.getRealm("foo"));
            });
        }
    });
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) UserSessionManager(org.keycloak.services.managers.UserSessionManager) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) UserManager(org.keycloak.models.UserManager) KeycloakSession(org.keycloak.models.KeycloakSession) ClientManager(org.keycloak.services.managers.ClientManager) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 8 with UserSessionManager

use of org.keycloak.services.managers.UserSessionManager in project keycloak by keycloak.

the class UserSessionProviderOfflineTest method reloadState.

public static void reloadState(KeycloakSession session, Boolean initialConfig) {
    currentSession = session;
    realm = currentSession.realms().getRealm("test");
    if (initialConfig) {
        currentSession.users().addUser(realm, "user1").setEmail("user1@localhost");
        currentSession.users().addUser(realm, "user2").setEmail("user2@localhost");
    }
    sessionManager = new UserSessionManager(currentSession);
}
Also used : UserSessionManager(org.keycloak.services.managers.UserSessionManager)

Example 9 with UserSessionManager

use of org.keycloak.services.managers.UserSessionManager in project keycloak by keycloak.

the class UserSessionProviderOfflineModelTest method testExpired.

@Test
public void testExpired() {
    // 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 {
        // Key is userSessionId, value is set of client UUIDS
        Map<String, Set<String>> offlineSessions = new HashMap<>();
        ClientModel[] testApp = new ClientModel[1];
        UserSessionModel[] origSessions = inComittedTransaction(session -> {
            // Create some online sessions in infinispan
            return UserSessionPersisterProviderTest.createSessions(session, realmId);
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            sessionManager = new UserSessionManager(session);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            // Persist 3 created userSessions and clientSessions as offline
            testApp[0] = realm.getClientByClientId("test-app");
            session.sessions().getUserSessionsStream(realm, testApp[0]).collect(Collectors.toList()).forEach(userSession -> offlineSessions.put(userSession.getId(), createOfflineSessionIncludeClientSessions(session, userSession)));
            // Assert all previously saved offline sessions found
            for (Map.Entry<String, Set<String>> entry : offlineSessions.entrySet()) {
                UserSessionModel foundSession = sessionManager.findOfflineUserSession(realm, entry.getKey());
                Assert.assertEquals(foundSession.getAuthenticatedClientSessions().keySet(), entry.getValue());
            }
        });
        log.info("Persisted 3 sessions to UserSessionPersisterProvider");
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            UserSessionModel session0 = session.sessions().getOfflineUserSession(realm, origSessions[0].getId());
            Assert.assertNotNull(session0);
            // sessions are in persister too
            Assert.assertEquals(3, persister.getUserSessionsCount(true));
            Time.setOffset(300);
            log.infof("Set time offset to 300. Time is: %d", Time.currentTime());
            // Set lastSessionRefresh to currentSession[0] to 0
            session0.setLastSessionRefresh(Time.currentTime());
        });
        // Increase timeOffset and update LSR of the session two times - first to 20 days and then to 21 days. At least one of updates
        // will propagate to PersisterLastSessionRefreshStore and update DB (Single update is not 100% sure as there is still a
        // chance of delayed periodic task to be run in the meantime and causing race-condition, which would mean LSR not updated in the DB)
        IntStream.range(0, 2).sequential().forEach(index -> inComittedTransaction(index, (session, i) -> {
            int timeOffset = 1728000 + (i * 86400);
            RealmModel realm = session.realms().getRealm(realmId);
            Time.setOffset(timeOffset);
            log.infof("Set time offset to %d. Time is: %d", timeOffset, Time.currentTime());
            UserSessionModel session0 = session.sessions().getOfflineUserSession(realm, origSessions[0].getId());
            session0.setLastSessionRefresh(Time.currentTime());
            return null;
        }));
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            // Increase timeOffset - 40 days
            Time.setOffset(3456000);
            log.infof("Set time offset to 3456000. Time is: %d", Time.currentTime());
            // Expire and ensure that all sessions despite session0 were removed
            persister.removeExpired(realm);
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            // assert session0 is the only session found
            Assert.assertNotNull(session.sessions().getOfflineUserSession(realm, origSessions[0].getId()));
            Assert.assertNull(session.sessions().getOfflineUserSession(realm, origSessions[1].getId()));
            Assert.assertNull(session.sessions().getOfflineUserSession(realm, origSessions[2].getId()));
            Assert.assertEquals(1, persister.getUserSessionsCount(true));
            // Expire everything and assert nothing found
            Time.setOffset(7000000);
            persister.removeExpired(realm);
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            sessionManager = new UserSessionManager(session);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            for (String userSessionId : offlineSessions.keySet()) {
                Assert.assertNull(sessionManager.findOfflineUserSession(realm, userSessionId));
            }
            Assert.assertEquals(0, persister.getUserSessionsCount(true));
        });
    } finally {
        Time.setOffset(0);
        kcSession.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
        if (timer != null) {
            timer.schedule(timerTaskCtx.getRunnable(), timerTaskCtx.getIntervalMillis(), PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
        }
        InfinispanTestUtil.revertTimeService();
    }
}
Also used : ClientModel(org.keycloak.models.ClientModel) IntStream(java.util.stream.IntStream) UserSessionProvider(org.keycloak.models.UserSessionProvider) Constants(org.keycloak.models.Constants) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Cache(org.infinispan.Cache) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) UserModel(org.keycloak.models.UserModel) RealmProvider(org.keycloak.models.RealmProvider) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) Map(java.util.Map) RequireProvider(org.keycloak.testsuite.model.RequireProvider) LinkedList(java.util.LinkedList) TimerProvider(org.keycloak.timer.TimerProvider) Time(org.keycloak.common.util.Time) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) InfinispanTestUtil(org.keycloak.testsuite.model.infinispan.InfinispanTestUtil) UserManager(org.keycloak.models.UserManager) RealmModel(org.keycloak.models.RealmModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) Test(org.junit.Test) PersisterLastSessionRefreshStoreFactory(org.keycloak.models.sessions.infinispan.changes.sessions.PersisterLastSessionRefreshStoreFactory) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest) UserSessionModel(org.keycloak.models.UserSessionModel) Collectors(java.util.stream.Collectors) UserProvider(org.keycloak.models.UserProvider) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) UserSessionManager(org.keycloak.services.managers.UserSessionManager) ResetTimeOffsetEvent(org.keycloak.models.utils.ResetTimeOffsetEvent) Assert(org.junit.Assert) UserSessionModel(org.keycloak.models.UserSessionModel) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) RealmModel(org.keycloak.models.RealmModel) UserSessionManager(org.keycloak.services.managers.UserSessionManager) ClientModel(org.keycloak.models.ClientModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) ResetTimeOffsetEvent(org.keycloak.models.utils.ResetTimeOffsetEvent) TimerProvider(org.keycloak.timer.TimerProvider) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 10 with UserSessionManager

use of org.keycloak.services.managers.UserSessionManager in project keycloak by keycloak.

the class UserSessionProviderOfflineModelTest method createOfflineSessionIncludeClientSessions.

private static Set<String> createOfflineSessionIncludeClientSessions(KeycloakSession session, UserSessionModel userSession) {
    Set<String> offlineSessions = new HashSet<>();
    UserSessionManager localManager = new UserSessionManager(session);
    for (AuthenticatedClientSessionModel clientSession : userSession.getAuthenticatedClientSessions().values()) {
        localManager.createOrUpdateOfflineSession(clientSession, userSession);
        offlineSessions.add(clientSession.getClient().getId());
    }
    return offlineSessions;
}
Also used : UserSessionManager(org.keycloak.services.managers.UserSessionManager) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) HashSet(java.util.HashSet)

Aggregations

UserSessionManager (org.keycloak.services.managers.UserSessionManager)15 UserSessionModel (org.keycloak.models.UserSessionModel)11 ClientModel (org.keycloak.models.ClientModel)9 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)8 HashSet (java.util.HashSet)6 KeycloakSession (org.keycloak.models.KeycloakSession)6 RealmModel (org.keycloak.models.RealmModel)6 UserModel (org.keycloak.models.UserModel)6 Test (org.junit.Test)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 Set (java.util.Set)4 Collectors (java.util.stream.Collectors)4 Consumes (javax.ws.rs.Consumes)4 POST (javax.ws.rs.POST)4 LinkedList (java.util.LinkedList)3 List (java.util.List)3 Objects (java.util.Objects)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 Context (javax.ws.rs.core.Context)3