Search in sources :

Example 41 with UserSessionModel

use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.

the class UserSessionProviderTest method testOnClientRemoved.

@Test
@ModelTest
public void testOnClientRemoved(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);
    String thirdPartyClientUUID = realm.getClientByClientId("third-party").getId();
    Map<String, Set<String>> clientSessionsKept = new HashMap<>();
    for (UserSessionModel s : sessions) {
        Set<String> clientUUIDS = new HashSet<>(s.getAuthenticatedClientSessions().keySet());
        // This client will be later removed, hence his clientSessions too
        clientUUIDS.remove(thirdPartyClientUUID);
        clientSessionsKept.put(s.getId(), clientUUIDS);
    }
    realm.removeClient(thirdPartyClientUUID);
    for (UserSessionModel s : sessions) {
        s = session.sessions().getUserSession(realm, s.getId());
        Set<String> clientUUIDS = s.getAuthenticatedClientSessions().keySet();
        assertEquals(clientUUIDS, clientSessionsKept.get(s.getId()));
    }
    // Revert client
    realm.addClient("third-party");
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) HashSet(java.util.HashSet) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 42 with UserSessionModel

use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.

the class UserSessionProviderTest method createSessions.

private static UserSessionModel[] createSessions(KeycloakSession session) {
    UserSessionModel[] sessions = new UserSessionModel[3];
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {
        RealmModel realm = kcSession.realms().getRealmByName("test");
        sessions[0] = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null);
        createClientSession(kcSession, realm.getClientByClientId("test-app"), sessions[0], "http://redirect", "state");
        createClientSession(kcSession, realm.getClientByClientId("third-party"), sessions[0], "http://redirect", "state");
        sessions[1] = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null);
        createClientSession(kcSession, realm.getClientByClientId("test-app"), sessions[1], "http://redirect", "state");
        sessions[2] = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.3", "form", true, null, null);
        createClientSession(kcSession, realm.getClientByClientId("test-app"), sessions[2], "http://redirect", "state");
    });
    return sessions;
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession)

Example 43 with UserSessionModel

use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.

the class UserSessionProviderTest method testTransientUserSession.

@Test
@ModelTest
public void testTransientUserSession(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    ClientModel client = realm.getClientByClientId("test-app");
    String userSessionId = UUID.randomUUID().toString();
    // create an user session, but don't persist it to infinispan
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> {
        long sessionsBefore = session1.sessions().getActiveUserSessions(realm, client);
        UserSessionModel userSession = session1.sessions().createUserSession(userSessionId, realm, session1.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null, UserSessionModel.SessionPersistenceState.TRANSIENT);
        AuthenticatedClientSessionModel clientSession = session1.sessions().createClientSession(realm, client, userSession);
        assertEquals(userSession, clientSession.getUserSession());
        assertSession(userSession, session.users().getUserByUsername(realm, "user1"), "127.0.0.1", userSession.getStarted(), userSession.getStarted(), "test-app");
        // Can find session by ID in current transaction
        UserSessionModel foundSession = session1.sessions().getUserSession(realm, userSessionId);
        Assert.assertEquals(userSession, foundSession);
        // Count of sessions should be still the same
        Assert.assertEquals(sessionsBefore, session1.sessions().getActiveUserSessions(realm, client));
    });
    // create an user session whose last refresh exceeds the max session idle timeout.
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> {
        UserSessionModel userSession = session1.sessions().getUserSession(realm, userSessionId);
        Assert.assertNull(userSession);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 44 with UserSessionModel

use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.

the class UserSessionProviderTest method testAuthenticatedClientSessions.

@Test
@ModelTest
public void testAuthenticatedClientSessions(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    realm.setSsoSessionIdleTimeout(1800);
    realm.setSsoSessionMaxLifespan(36000);
    UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null);
    ClientModel client1 = realm.getClientByClientId("test-app");
    ClientModel client2 = realm.getClientByClientId("third-party");
    // Create client1 session
    AuthenticatedClientSessionModel clientSession1 = session.sessions().createClientSession(realm, client1, userSession);
    clientSession1.setAction("foo1");
    int currentTime1 = Time.currentTime();
    clientSession1.setTimestamp(currentTime1);
    // Create client2 session
    AuthenticatedClientSessionModel clientSession2 = session.sessions().createClientSession(realm, client2, userSession);
    clientSession2.setAction("foo2");
    int currentTime2 = Time.currentTime();
    clientSession2.setTimestamp(currentTime2);
    // Ensure sessions are here
    userSession = session.sessions().getUserSession(realm, userSession.getId());
    Map<String, AuthenticatedClientSessionModel> clientSessions = userSession.getAuthenticatedClientSessions();
    Assert.assertEquals(2, clientSessions.size());
    testAuthenticatedClientSession(clientSessions.get(client1.getId()), "test-app", userSession.getId(), "foo1", currentTime1);
    testAuthenticatedClientSession(clientSessions.get(client2.getId()), "third-party", userSession.getId(), "foo2", currentTime2);
    // Update session1
    clientSessions.get(client1.getId()).setAction("foo1-updated");
    // Ensure updated
    userSession = session.sessions().getUserSession(realm, userSession.getId());
    clientSessions = userSession.getAuthenticatedClientSessions();
    testAuthenticatedClientSession(clientSessions.get(client1.getId()), "test-app", userSession.getId(), "foo1-updated", currentTime1);
    // Rewrite session2
    clientSession2 = session.sessions().createClientSession(realm, client2, userSession);
    clientSession2.setAction("foo2-rewrited");
    int currentTime3 = Time.currentTime();
    clientSession2.setTimestamp(currentTime3);
    // Ensure updated
    userSession = session.sessions().getUserSession(realm, userSession.getId());
    clientSessions = userSession.getAuthenticatedClientSessions();
    Assert.assertEquals(2, clientSessions.size());
    testAuthenticatedClientSession(clientSessions.get(client1.getId()), "test-app", userSession.getId(), "foo1-updated", currentTime1);
    testAuthenticatedClientSession(clientSessions.get(client2.getId()), "third-party", userSession.getId(), "foo2-rewrited", currentTime3);
    // remove session
    clientSession1 = userSession.getAuthenticatedClientSessions().get(client1.getId());
    clientSession1.detachFromUserSession();
    userSession = session.sessions().getUserSession(realm, userSession.getId());
    clientSessions = userSession.getAuthenticatedClientSessions();
    Assert.assertEquals(1, clientSessions.size());
    Assert.assertNull(clientSessions.get(client1.getId()));
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 45 with UserSessionModel

use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.

the class UserSessionProviderTest method testRemoveUserSessionsByExpiredRememberMe.

/**
 * Tests the removal of expired sessions with remember-me enabled. It differs from the non remember me scenario by
 * taking into consideration the specific remember-me timeout values.
 *
 * @param session the {@code KeycloakSession}
 */
@Test
@ModelTest
public void testRemoveUserSessionsByExpiredRememberMe(KeycloakSession session) {
    RealmModel testRealm = session.realms().getRealmByName("test");
    int previousMaxLifespan = testRealm.getSsoSessionMaxLifespanRememberMe();
    int previousMaxIdle = testRealm.getSsoSessionIdleTimeoutRememberMe();
    try {
        ClientModel client = testRealm.getClientByClientId("test-app");
        Set<String> validUserSessions = new HashSet<>();
        Set<String> validClientSessions = new HashSet<>();
        Set<String> expiredUserSessions = new HashSet<>();
        // first lets update the realm by setting remember-me timeout values, which will be 4 times higher than the default timeout values.
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {
            RealmModel r = kcSession.realms().getRealmByName("test");
            r.setSsoSessionMaxLifespanRememberMe(r.getSsoSessionMaxLifespan() * 4);
            r.setSsoSessionIdleTimeoutRememberMe(r.getSsoSessionIdleTimeout() * 4);
        });
        // update the realm reference so that the remember-me timeouts are now visible.
        RealmModel realm = session.realms().getRealmByName("test");
        // create an user session with remember-me enabled that is older than the default 'max lifespan' timeout but not older than the 'max lifespan remember-me' timeout.
        // the session's last refresh also exceeds the default 'session idle' timeout but doesn't exceed the 'session idle remember-me' timeout.
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {
            Time.setOffset(-(realm.getSsoSessionMaxLifespan() * 2));
            UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null);
            AuthenticatedClientSessionModel clientSession = kcSession.sessions().createClientSession(realm, client, userSession);
            assertEquals(userSession, clientSession.getUserSession());
            Time.setOffset(-(realm.getSsoSessionIdleTimeout() * 2));
            userSession.setLastSessionRefresh(Time.currentTime());
            clientSession.setTimestamp(Time.currentTime());
            validUserSessions.add(userSession.getId());
            validClientSessions.add(clientSession.getId());
        });
        // create an user session with remember-me enabled that is older than the 'max lifespan remember-me' timeout.
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {
            Time.setOffset(-(realm.getSsoSessionMaxLifespanRememberMe() + 1));
            UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null);
            expiredUserSessions.add(userSession.getId());
        });
        // finally create an user session with remember-me enabled whose last refresh exceeds the 'session idle remember-me' timeout.
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {
            Time.setOffset(-(realm.getSsoSessionIdleTimeoutRememberMe() + SessionTimeoutHelper.PERIODIC_CLEANER_IDLE_TIMEOUT_WINDOW_SECONDS + 1));
            UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.1", "form", true, null, null);
            // no need to explicitly set the last refresh time - it is the same as the creation time.
            expiredUserSessions.add(userSession.getId());
        });
        // remove the expired sessions - the first session should not be removed as it doesn't exceed any of the remember-me timeout values.
        Time.setOffset(0);
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> kcSession.sessions().removeExpired(realm));
        for (String sessionId : expiredUserSessions) {
            assertNull(session.sessions().getUserSession(realm, sessionId));
        }
        for (String sessionId : validUserSessions) {
            UserSessionModel userSessionLoaded = session.sessions().getUserSession(realm, sessionId);
            assertNotNull(userSessionLoaded);
            // the only valid user session should also have a valid client session that hasn't expired.
            AuthenticatedClientSessionModel clientSessionModel = userSessionLoaded.getAuthenticatedClientSessions().get(client.getId());
            assertNotNull(clientSessionModel);
            assertTrue(validClientSessions.contains(clientSessionModel.getId()));
        }
    } finally {
        Time.setOffset(0);
        session.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
        // restore the original remember-me timeout values in the realm.
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {
            RealmModel r = kcSession.realms().getRealmByName("test");
            r.setSsoSessionMaxLifespanRememberMe(previousMaxLifespan);
            r.setSsoSessionIdleTimeoutRememberMe(previousMaxIdle);
        });
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) ResetTimeOffsetEvent(org.keycloak.models.utils.ResetTimeOffsetEvent) KeycloakSession(org.keycloak.models.KeycloakSession) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) HashSet(java.util.HashSet) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

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