Search in sources :

Example 1 with AuthenticatedClientSessionStore

use of org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore in project keycloak by keycloak.

the class InfinispanUserSessionProvider method importClientSession.

private AuthenticatedClientSessionAdapter importClientSession(UserSessionAdapter sessionToImportInto, AuthenticatedClientSessionModel clientSession, InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx, InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx, boolean offline) {
    AuthenticatedClientSessionEntity entity = createAuthenticatedClientSessionInstance(clientSession, sessionToImportInto.getRealm().getId(), offline);
    final UUID clientSessionId = entity.getId();
    SessionUpdateTask<AuthenticatedClientSessionEntity> createClientSessionTask = Tasks.addIfAbsentSync();
    clientSessionUpdateTx.addTask(entity.getId(), createClientSessionTask, entity, UserSessionModel.SessionPersistenceState.PERSISTENT);
    AuthenticatedClientSessionStore clientSessions = sessionToImportInto.getEntity().getAuthenticatedClientSessions();
    clientSessions.put(clientSession.getClient().getId(), clientSessionId);
    SessionUpdateTask registerClientSessionTask = new RegisterClientSessionTask(clientSession.getClient().getId(), clientSessionId);
    userSessionUpdateTx.addTask(sessionToImportInto.getId(), registerClientSessionTask);
    return new AuthenticatedClientSessionAdapter(session, this, entity, clientSession.getClient(), sessionToImportInto, clientSessionUpdateTx, offline);
}
Also used : AuthenticatedClientSessionEntity(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionEntity) UUID(java.util.UUID) SessionUpdateTask(org.keycloak.models.sessions.infinispan.changes.SessionUpdateTask) AuthenticatedClientSessionStore(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore)

Example 2 with AuthenticatedClientSessionStore

use of org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore in project keycloak by keycloak.

the class UserSessionAdapter method getAuthenticatedClientSessionByClient.

@Override
public AuthenticatedClientSessionModel getAuthenticatedClientSessionByClient(String clientUUID) {
    AuthenticatedClientSessionStore clientSessionEntities = entity.getAuthenticatedClientSessions();
    final UUID clientSessionId = clientSessionEntities.get(clientUUID);
    if (clientSessionId == null) {
        return null;
    }
    ClientModel client = realm.getClientById(clientUUID);
    if (client != null) {
        return provider.getClientSession(this, client, clientSessionId, offline);
    }
    removeAuthenticatedClientSessions(Collections.singleton(clientUUID));
    return null;
}
Also used : ClientModel(org.keycloak.models.ClientModel) UUID(java.util.UUID) AuthenticatedClientSessionStore(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore)

Example 3 with AuthenticatedClientSessionStore

use of org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore in project keycloak by keycloak.

the class UserSessionAdapter method getAuthenticatedClientSessions.

@Override
public Map<String, AuthenticatedClientSessionModel> getAuthenticatedClientSessions() {
    AuthenticatedClientSessionStore clientSessionEntities = entity.getAuthenticatedClientSessions();
    Map<String, AuthenticatedClientSessionModel> result = new HashMap<>();
    List<String> removedClientUUIDS = new LinkedList<>();
    if (clientSessionEntities != null) {
        clientSessionEntities.forEach((String key, UUID value) -> {
            // Check if client still exists
            ClientModel client = realm.getClientById(key);
            if (client != null) {
                final AuthenticatedClientSessionAdapter clientSession = provider.getClientSession(this, client, value, offline);
                if (clientSession != null) {
                    result.put(key, clientSession);
                }
            } else {
                removedClientUUIDS.add(key);
            }
        });
    }
    removeAuthenticatedClientSessions(removedClientUUIDS);
    return Collections.unmodifiableMap(result);
}
Also used : ClientModel(org.keycloak.models.ClientModel) HashMap(java.util.HashMap) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) UUID(java.util.UUID) AuthenticatedClientSessionStore(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore) LinkedList(java.util.LinkedList)

Example 4 with AuthenticatedClientSessionStore

use of org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore in project keycloak by keycloak.

the class InfinispanUserSessionProvider method createUserSessionEntityInstance.

private UserSessionEntity createUserSessionEntityInstance(UserSessionModel userSession) {
    UserSessionEntity entity = new UserSessionEntity();
    entity.setId(userSession.getId());
    entity.setRealmId(userSession.getRealm().getId());
    entity.setAuthMethod(userSession.getAuthMethod());
    entity.setBrokerSessionId(userSession.getBrokerSessionId());
    entity.setBrokerUserId(userSession.getBrokerUserId());
    entity.setIpAddress(userSession.getIpAddress());
    entity.setNotes(userSession.getNotes() == null ? new ConcurrentHashMap<>() : userSession.getNotes());
    entity.setAuthenticatedClientSessions(new AuthenticatedClientSessionStore());
    entity.setRememberMe(userSession.isRememberMe());
    entity.setState(userSession.getState());
    if (userSession instanceof OfflineUserSessionModel) {
        // this is a hack so that UserModel doesn't have to be available when offline token is imported.
        // see related JIRA - KEYCLOAK-5350 and corresponding test
        OfflineUserSessionModel oline = (OfflineUserSessionModel) userSession;
        entity.setUser(oline.getUserId());
    // NOTE: Hack
    // We skip calling entity.setLoginUsername(userSession.getLoginUsername())
    } else {
        entity.setLoginUsername(userSession.getLoginUsername());
        entity.setUser(userSession.getUser().getId());
    }
    entity.setStarted(userSession.getStarted());
    entity.setLastSessionRefresh(userSession.getLastSessionRefresh());
    return entity;
}
Also used : OfflineUserSessionModel(org.keycloak.models.OfflineUserSessionModel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AuthenticatedClientSessionStore(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)

Example 5 with AuthenticatedClientSessionStore

use of org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore in project keycloak by keycloak.

the class InfinispanUserSessionProvider method importUserSessions.

@Override
public void importUserSessions(Collection<UserSessionModel> persistentUserSessions, boolean offline) {
    if (persistentUserSessions == null || persistentUserSessions.isEmpty()) {
        return;
    }
    Map<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionsById = new HashMap<>();
    Map<String, SessionEntityWrapper<UserSessionEntity>> sessionsById = persistentUserSessions.stream().map((UserSessionModel persistentUserSession) -> {
        UserSessionEntity userSessionEntityToImport = createUserSessionEntityInstance(persistentUserSession);
        for (Map.Entry<String, AuthenticatedClientSessionModel> entry : persistentUserSession.getAuthenticatedClientSessions().entrySet()) {
            String clientUUID = entry.getKey();
            AuthenticatedClientSessionModel clientSession = entry.getValue();
            AuthenticatedClientSessionEntity clientSessionToImport = createAuthenticatedClientSessionInstance(clientSession, userSessionEntityToImport.getRealmId(), offline);
            // Update timestamp to same value as userSession. LastSessionRefresh of userSession from DB will have correct value
            clientSessionToImport.setTimestamp(userSessionEntityToImport.getLastSessionRefresh());
            clientSessionsById.put(clientSessionToImport.getId(), new SessionEntityWrapper<>(clientSessionToImport));
            // Update userSession entity with the clientSession
            AuthenticatedClientSessionStore clientSessions = userSessionEntityToImport.getAuthenticatedClientSessions();
            clientSessions.put(clientUUID, clientSessionToImport.getId());
        }
        return userSessionEntityToImport;
    }).map(SessionEntityWrapper::new).collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
    // Directly put all entities to the infinispan cache
    Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = CacheDecorators.skipCacheLoaders(getCache(offline));
    boolean importWithExpiration = sessionsById.size() == 1;
    if (importWithExpiration) {
        importSessionsWithExpiration(sessionsById, cache, offline ? SessionTimeouts::getOfflineSessionLifespanMs : SessionTimeouts::getUserSessionLifespanMs, offline ? SessionTimeouts::getOfflineSessionMaxIdleMs : SessionTimeouts::getUserSessionMaxIdleMs);
    } else {
        cache.putAll(sessionsById);
    }
    // put all entities to the remoteCache (if exists)
    RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);
    if (remoteCache != null) {
        Map<String, SessionEntityWrapper<UserSessionEntity>> sessionsByIdForTransport = sessionsById.values().stream().map(SessionEntityWrapper::forTransport).collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
        if (importWithExpiration) {
            importSessionsWithExpiration(sessionsByIdForTransport, remoteCache, offline ? SessionTimeouts::getOfflineSessionLifespanMs : SessionTimeouts::getUserSessionLifespanMs, offline ? SessionTimeouts::getOfflineSessionMaxIdleMs : SessionTimeouts::getUserSessionMaxIdleMs);
        } else {
            Retry.executeWithBackoff((int iteration) -> {
                try {
                    remoteCache.putAll(sessionsByIdForTransport);
                } 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", sessionsByIdForTransport.size(), iteration);
                    }
                    // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
                    throw re;
                }
            }, 10, 10);
        }
    }
    // Import client sessions
    Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessCache = offline ? offlineClientSessionCache : clientSessionCache;
    clientSessCache = CacheDecorators.skipCacheLoaders(clientSessCache);
    if (importWithExpiration) {
        importSessionsWithExpiration(clientSessionsById, clientSessCache, offline ? SessionTimeouts::getOfflineClientSessionLifespanMs : SessionTimeouts::getClientSessionLifespanMs, offline ? SessionTimeouts::getOfflineClientSessionMaxIdleMs : SessionTimeouts::getClientSessionMaxIdleMs);
    } else {
        clientSessCache.putAll(clientSessionsById);
    }
    // put all entities to the remoteCache (if exists)
    RemoteCache remoteCacheClientSessions = InfinispanUtil.getRemoteCache(clientSessCache);
    if (remoteCacheClientSessions != null) {
        Map<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> sessionsByIdForTransport = clientSessionsById.values().stream().map(SessionEntityWrapper::forTransport).collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
        if (importWithExpiration) {
            importSessionsWithExpiration(sessionsByIdForTransport, remoteCacheClientSessions, offline ? SessionTimeouts::getOfflineClientSessionLifespanMs : SessionTimeouts::getClientSessionLifespanMs, offline ? SessionTimeouts::getOfflineClientSessionMaxIdleMs : SessionTimeouts::getClientSessionMaxIdleMs);
        } else {
            Retry.executeWithBackoff((int iteration) -> {
                try {
                    remoteCacheClientSessions.putAll(sessionsByIdForTransport);
                } catch (HotRodClientException re) {
                    if (log.isDebugEnabled()) {
                        log.debugf(re, "Failed to put import %d client sessions to remoteCache. Iteration '%s'. Will try to retry the task", sessionsByIdForTransport.size(), iteration);
                    }
                    // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
                    throw re;
                }
            }, 10, 10);
        }
    }
}
Also used : UserSessionProvider(org.keycloak.models.UserSessionProvider) RemoveUserSessionsEvent(org.keycloak.models.sessions.infinispan.events.RemoveUserSessionsEvent) BiFunction(java.util.function.BiFunction) Cache(org.infinispan.Cache) RemoteCache(org.infinispan.client.hotrod.RemoteCache) FuturesHelper(org.keycloak.models.sessions.infinispan.util.FuturesHelper) ClusterProvider(org.keycloak.cluster.ClusterProvider) PersisterLastSessionRefreshStore(org.keycloak.models.sessions.infinispan.changes.sessions.PersisterLastSessionRefreshStore) Future(java.util.concurrent.Future) RealmRemovedSessionEvent(org.keycloak.models.sessions.infinispan.events.RealmRemovedSessionEvent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) Map(java.util.Map) SessionEntity(org.keycloak.models.sessions.infinispan.entities.SessionEntity) Time(org.keycloak.common.util.Time) InfinispanUtil(org.keycloak.connections.infinispan.InfinispanUtil) OfflineUserSessionModel(org.keycloak.models.OfflineUserSessionModel) RealmModel(org.keycloak.models.RealmModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) CrossDCLastSessionRefreshStore(org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStore) SessionPredicate(org.keycloak.models.sessions.infinispan.stream.SessionPredicate) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) Objects(java.util.Objects) UserProvider(org.keycloak.models.UserProvider) InfinispanChangelogBasedTransaction(org.keycloak.models.sessions.infinispan.changes.InfinispanChangelogBasedTransaction) Stream(java.util.stream.Stream) Flag(org.infinispan.context.Flag) AuthenticatedClientSessionEntity(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionEntity) DeviceActivityManager(org.keycloak.device.DeviceActivityManager) ClientModel(org.keycloak.models.ClientModel) Mappers(org.keycloak.models.sessions.infinispan.stream.Mappers) InfinispanKeyGenerator(org.keycloak.models.sessions.infinispan.util.InfinispanKeyGenerator) Logger(org.jboss.logging.Logger) UserSessionSpi(org.keycloak.models.UserSessionSpi) HashMap(java.util.HashMap) Function(java.util.function.Function) HotRodClientException(org.infinispan.client.hotrod.exceptions.HotRodClientException) UserModel(org.keycloak.models.UserModel) AuthenticatedClientSessionStore(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore) SessionTimeouts(org.keycloak.models.sessions.infinispan.util.SessionTimeouts) BasicCache(org.infinispan.commons.api.BasicCache) UserSessionPredicate(org.keycloak.models.sessions.infinispan.stream.UserSessionPredicate) StreamSupport(java.util.stream.StreamSupport) Retry(org.keycloak.common.util.Retry) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity) RemoteCacheInvoker(org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheInvoker) Iterator(java.util.Iterator) SessionUpdateTask(org.keycloak.models.sessions.infinispan.changes.SessionUpdateTask) KeycloakSession(org.keycloak.models.KeycloakSession) UserSessionModel(org.keycloak.models.UserSessionModel) CacheCollectors(org.infinispan.stream.CacheCollectors) Comparators(org.keycloak.models.sessions.infinispan.stream.Comparators) Tasks(org.keycloak.models.sessions.infinispan.changes.Tasks) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ModelException(org.keycloak.models.ModelException) StreamsUtil.paginatedStream(org.keycloak.utils.StreamsUtil.paginatedStream) SessionEventsSenderTransaction(org.keycloak.models.sessions.infinispan.events.SessionEventsSenderTransaction) Collections(java.util.Collections) OfflineUserSessionModel(org.keycloak.models.OfflineUserSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) HotRodClientException(org.infinispan.client.hotrod.exceptions.HotRodClientException) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper) AuthenticatedClientSessionEntity(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionEntity) RemoteCache(org.infinispan.client.hotrod.RemoteCache) UUID(java.util.UUID) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) AuthenticatedClientSessionStore(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)

Aggregations

AuthenticatedClientSessionStore (org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore)5 UUID (java.util.UUID)4 ClientModel (org.keycloak.models.ClientModel)3 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)2 OfflineUserSessionModel (org.keycloak.models.OfflineUserSessionModel)2 UserSessionEntity (org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)2 Serializable (java.io.Serializable)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Set (java.util.Set)1 Future (java.util.concurrent.Future)1 TimeUnit (java.util.concurrent.TimeUnit)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 BiFunction (java.util.function.BiFunction)1