Search in sources :

Example 6 with KeycloakSession

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());
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) KeycloakSession(org.keycloak.models.KeycloakSession) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 7 with KeycloakSession

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());
        }
    });
}
Also used : UserModel(org.keycloak.models.UserModel) RemoteCacheInvoker(org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheInvoker) KeycloakSession(org.keycloak.models.KeycloakSession) UserLoginFailureProvider(org.keycloak.models.UserLoginFailureProvider) PostMigrationEvent(org.keycloak.models.utils.PostMigrationEvent)

Example 8 with KeycloakSession

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");
}
Also used : UserSessionProvider(org.keycloak.models.UserSessionProvider) ClusterProvider(org.keycloak.cluster.ClusterProvider) KeycloakSession(org.keycloak.models.KeycloakSession) RemoveUserSessionsEvent(org.keycloak.models.sessions.infinispan.events.RemoveUserSessionsEvent) ClientRemovedSessionEvent(org.keycloak.models.sessions.infinispan.events.ClientRemovedSessionEvent) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) RealmRemovedSessionEvent(org.keycloak.models.sessions.infinispan.events.RealmRemovedSessionEvent)

Example 9 with KeycloakSession

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();
                }
            }
        }
    });
}
Also used : ProviderEventListener(org.keycloak.provider.ProviderEventListener) ProviderEvent(org.keycloak.provider.ProviderEvent) UserModel(org.keycloak.models.UserModel) UserSessionProvider(org.keycloak.models.UserSessionProvider) ResetTimeOffsetEvent(org.keycloak.models.utils.ResetTimeOffsetEvent) KeycloakSession(org.keycloak.models.KeycloakSession) InfinispanKeyGenerator(org.keycloak.models.sessions.infinispan.util.InfinispanKeyGenerator) PostMigrationEvent(org.keycloak.models.utils.PostMigrationEvent)

Example 10 with KeycloakSession

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;
        }
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UsersExportStrategy(org.keycloak.exportimport.UsersExportStrategy) KeycloakSession(org.keycloak.models.KeycloakSession) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) IOException(java.io.IOException)

Aggregations

KeycloakSession (org.keycloak.models.KeycloakSession)189 RealmModel (org.keycloak.models.RealmModel)136 UserModel (org.keycloak.models.UserModel)78 Test (org.junit.Test)76 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)61 ClientModel (org.keycloak.models.ClientModel)58 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)53 List (java.util.List)34 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 Collectors (java.util.stream.Collectors)21 IOException (java.io.IOException)20 Map (java.util.Map)19 UserSessionModel (org.keycloak.models.UserSessionModel)19 ArrayList (java.util.ArrayList)18 ClientScopeModel (org.keycloak.models.ClientScopeModel)18 RoleModel (org.keycloak.models.RoleModel)18 Set (java.util.Set)16 RealmManager (org.keycloak.services.managers.RealmManager)16 HashMap (java.util.HashMap)14 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)14