Search in sources :

Example 16 with RealmModel

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

the class InfinispanUserSessionProvider method importSessionsWithExpiration.

private <T extends SessionEntity> void importSessionsWithExpiration(Map<? extends Object, SessionEntityWrapper<T>> sessionsById, BasicCache cache, BiFunction<RealmModel, T, Long> lifespanMsCalculator, BiFunction<RealmModel, T, Long> maxIdleTimeMsCalculator) {
    sessionsById.forEach((id, sessionEntityWrapper) -> {
        T sessionEntity = sessionEntityWrapper.getEntity();
        RealmModel currentRealm = session.realms().getRealm(sessionEntity.getRealmId());
        long lifespan = lifespanMsCalculator.apply(currentRealm, sessionEntity);
        long maxIdle = maxIdleTimeMsCalculator.apply(currentRealm, sessionEntity);
        if (lifespan != SessionTimeouts.ENTRY_EXPIRED_FLAG && maxIdle != SessionTimeouts.ENTRY_EXPIRED_FLAG) {
            if (cache instanceof RemoteCache) {
                Retry.executeWithBackoff((int iteration) -> {
                    try {
                        cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
                    } catch (HotRodClientException re) {
                        if (log.isDebugEnabled()) {
                            log.debugf(re, "Failed to put import %d sessions to remoteCache. Iteration '%s'. Will try to retry the task", sessionsById.size(), iteration);
                        }
                        // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
                        throw re;
                    }
                }, 10, 10);
            } else {
                cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
            }
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) RemoteCache(org.infinispan.client.hotrod.RemoteCache) HotRodClientException(org.infinispan.client.hotrod.exceptions.HotRodClientException)

Example 17 with RealmModel

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

the class InfinispanUserLoginFailureProviderFactory method checkRemoteCaches.

protected void checkRemoteCaches(KeycloakSession session) {
    InfinispanConnectionProvider ispn = session.getProvider(InfinispanConnectionProvider.class);
    Cache<LoginFailureKey, SessionEntityWrapper<LoginFailureEntity>> loginFailuresCache = ispn.getCache(InfinispanConnectionProvider.LOGIN_FAILURE_CACHE_NAME);
    checkRemoteCache(session, loginFailuresCache, (RealmModel realm) -> Time.toMillis(realm.getMaxDeltaTimeSeconds()), SessionTimeouts::getLoginFailuresLifespanMs, SessionTimeouts::getLoginFailuresMaxIdleMs);
}
Also used : RealmModel(org.keycloak.models.RealmModel) SessionTimeouts(org.keycloak.models.sessions.infinispan.util.SessionTimeouts) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) LoginFailureKey(org.keycloak.models.sessions.infinispan.entities.LoginFailureKey) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)

Example 18 with RealmModel

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

the class InfinispanUserSessionProviderFactory method checkRemoteCaches.

protected void checkRemoteCaches(KeycloakSession session) {
    this.remoteCacheInvoker = new RemoteCacheInvoker();
    InfinispanConnectionProvider ispn = session.getProvider(InfinispanConnectionProvider.class);
    Cache<String, SessionEntityWrapper<UserSessionEntity>> sessionsCache = ispn.getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);
    RemoteCache sessionsRemoteCache = checkRemoteCache(session, sessionsCache, (RealmModel realm) -> {
        // We won't write to the remoteCache during token refresh, so the timeout needs to be longer.
        return Time.toMillis(realm.getSsoSessionMaxLifespan());
    }, SessionTimeouts::getUserSessionLifespanMs, SessionTimeouts::getUserSessionMaxIdleMs);
    if (sessionsRemoteCache != null) {
        lastSessionRefreshStore = new CrossDCLastSessionRefreshStoreFactory().createAndInit(session, sessionsCache, false);
    }
    Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionsCache = ispn.getCache(InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME);
    checkRemoteCache(session, clientSessionsCache, (RealmModel realm) -> {
        // We won't write to the remoteCache during token refresh, so the timeout needs to be longer.
        return Time.toMillis(realm.getSsoSessionMaxLifespan());
    }, SessionTimeouts::getClientSessionLifespanMs, SessionTimeouts::getClientSessionMaxIdleMs);
    Cache<String, SessionEntityWrapper<UserSessionEntity>> offlineSessionsCache = ispn.getCache(InfinispanConnectionProvider.OFFLINE_USER_SESSION_CACHE_NAME);
    RemoteCache offlineSessionsRemoteCache = checkRemoteCache(session, offlineSessionsCache, (RealmModel realm) -> {
        return Time.toMillis(realm.getOfflineSessionIdleTimeout());
    }, SessionTimeouts::getOfflineSessionLifespanMs, SessionTimeouts::getOfflineSessionMaxIdleMs);
    if (offlineSessionsRemoteCache != null) {
        offlineLastSessionRefreshStore = new CrossDCLastSessionRefreshStoreFactory().createAndInit(session, offlineSessionsCache, true);
    }
    Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionsCache = ispn.getCache(InfinispanConnectionProvider.OFFLINE_CLIENT_SESSION_CACHE_NAME);
    checkRemoteCache(session, offlineClientSessionsCache, (RealmModel realm) -> {
        return Time.toMillis(realm.getOfflineSessionIdleTimeout());
    }, SessionTimeouts::getOfflineClientSessionLifespanMs, SessionTimeouts::getOfflineClientSessionMaxIdleMs);
}
Also used : RealmModel(org.keycloak.models.RealmModel) CrossDCLastSessionRefreshStoreFactory(org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStoreFactory) RemoteCacheInvoker(org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheInvoker) RemoteCache(org.infinispan.client.hotrod.RemoteCache) SessionTimeouts(org.keycloak.models.sessions.infinispan.util.SessionTimeouts) UUID(java.util.UUID) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)

Example 19 with RealmModel

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

the class InfinispanChangelogBasedTransaction method addTask.

// Create entity and new version for it
public void addTask(K key, SessionUpdateTask<V> task, V entity, UserSessionModel.SessionPersistenceState persistenceState) {
    if (entity == null) {
        throw new IllegalArgumentException("Null entity not allowed");
    }
    RealmModel realm = kcSession.realms().getRealm(entity.getRealmId());
    SessionEntityWrapper<V> wrappedEntity = new SessionEntityWrapper<>(entity);
    SessionUpdatesList<V> myUpdates = new SessionUpdatesList<>(realm, wrappedEntity, persistenceState);
    updates.put(key, myUpdates);
    // Run the update now, so reader in same transaction can see it
    task.runUpdate(entity);
    myUpdates.add(task);
}
Also used : RealmModel(org.keycloak.models.RealmModel)

Example 20 with RealmModel

use of org.keycloak.models.RealmModel 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

RealmModel (org.keycloak.models.RealmModel)591 Test (org.junit.Test)249 UserModel (org.keycloak.models.UserModel)225 KeycloakSession (org.keycloak.models.KeycloakSession)152 ClientModel (org.keycloak.models.ClientModel)149 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)90 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)84 ComponentModel (org.keycloak.component.ComponentModel)83 RoleModel (org.keycloak.models.RoleModel)73 UserSessionModel (org.keycloak.models.UserSessionModel)64 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)62 List (java.util.List)55 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)51 GroupModel (org.keycloak.models.GroupModel)47 HashMap (java.util.HashMap)38 Collectors (java.util.stream.Collectors)34 CachedUserModel (org.keycloak.models.cache.CachedUserModel)34 Path (javax.ws.rs.Path)30 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)30 Map (java.util.Map)29