Search in sources :

Example 6 with KeycloakSessionFactory

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

the class ProtocolMapperUtils method getSortedProtocolMappers.

public static Stream<Entry<ProtocolMapperModel, ProtocolMapper>> getSortedProtocolMappers(KeycloakSession session, ClientSessionContext ctx) {
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    return ctx.getProtocolMappersStream().flatMap(mapperModel -> {
        ProtocolMapper mapper = (ProtocolMapper) sessionFactory.getProviderFactory(ProtocolMapper.class, mapperModel.getProtocolMapper());
        if (mapper == null)
            return null;
        Map<ProtocolMapperModel, ProtocolMapper> protocolMapperMap = new HashMap<>();
        protocolMapperMap.put(mapperModel, mapper);
        return protocolMapperMap.entrySet().stream();
    }).filter(Objects::nonNull).sorted(Comparator.comparing(ProtocolMapperUtils::compare));
}
Also used : HashMap(java.util.HashMap) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel)

Example 7 with KeycloakSessionFactory

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

the class NginxProxySslClientCertificateLookup method loadKeycloakTrustStore.

/**
 *  Loading truststore @ first login
 *
 * @param kcsession
 * @return
 */
public boolean loadKeycloakTrustStore(KeycloakSession kcsession) {
    if (!isTruststoreLoaded) {
        log.debug(" Loading Keycloak truststore ...");
        KeycloakSessionFactory factory = kcsession.getKeycloakSessionFactory();
        TruststoreProviderFactory truststoreFactory = (TruststoreProviderFactory) factory.getProviderFactory(TruststoreProvider.class, "file");
        TruststoreProvider provider = truststoreFactory.create(kcsession);
        if (provider != null && provider.getTruststore() != null) {
            truststore = provider.getTruststore();
            trustedRootCerts = new HashSet<>(provider.getRootCertificates().values());
            intermediateCerts = new HashSet<>(provider.getIntermediateCertificates().values());
            log.debug("Keycloak truststore loaded for NGINX x509cert-lookup provider.");
            isTruststoreLoaded = true;
        }
    }
    return isTruststoreLoaded;
}
Also used : TruststoreProviderFactory(org.keycloak.truststore.TruststoreProviderFactory) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) TruststoreProvider(org.keycloak.truststore.TruststoreProvider)

Example 8 with KeycloakSessionFactory

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

the class SyncFederationTest method test01PeriodicSyncOnCreate.

/**
 * Test that period sync is triggered when creating a synchronized User Storage Provider
 */
@Test
public void test01PeriodicSyncOnCreate() {
    final Map<String, Integer> state = testingClient.server().fetch(session -> {
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        DummyUserFederationProviderFactory dummyFedFactory = (DummyUserFederationProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, DummyUserFederationProviderFactory.PROVIDER_NAME);
        int full = dummyFedFactory.getFullSyncCounter();
        int changed = dummyFedFactory.getChangedSyncCounter();
        Map<String, Integer> state1 = new HashMap<>();
        state1.put("full", full);
        state1.put("changed", changed);
        return state1;
    }, Map.class);
    // Enable timer for SyncDummyUserFederationProvider
    testingClient.server().run(session -> {
        RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST);
        UserStorageProviderModel model = new UserStorageProviderModel();
        model.setProviderId(DummyUserFederationProviderFactory.PROVIDER_NAME);
        model.setPriority(1);
        model.setName("test-sync-dummy");
        model.setFullSyncPeriod(-1);
        model.setChangedSyncPeriod(1);
        model.setLastSync(0);
        ComponentModel dummyModel = new UserStorageProviderModel(appRealm.addComponentModel(model));
    });
    testingClient.server().run(session -> {
        RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST);
        UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm);
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        DummyUserFederationProviderFactory dummyFedFactory = (DummyUserFederationProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, DummyUserFederationProviderFactory.PROVIDER_NAME);
        // Assert that after some period was DummyUserFederationProvider triggered
        UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
        sleep(1800);
        // Cancel timer
        usersSyncManager.notifyToRefreshPeriodicSync(session, appRealm, dummyModel, true);
        log.infof("Notified sync manager about cancel periodic sync");
        // This sync is here just to ensure that we have lock (doublecheck that periodic sync, which was possibly triggered before canceling timer is finished too)
        while (true) {
            SynchronizationResult result = usersSyncManager.syncChangedUsers(session.getKeycloakSessionFactory(), appRealm.getId(), dummyModel);
            if (result.isIgnored()) {
                log.infof("Still waiting for lock before periodic sync is finished", result.toString());
                sleep(1000);
            } else {
                break;
            }
        }
        int full = state.get("full");
        int changed = state.get("changed");
        // Assert that DummyUserFederationProviderFactory.syncChangedUsers was invoked at least 2 times (once periodically and once for us)
        int newChanged = dummyFedFactory.getChangedSyncCounter();
        Assert.assertEquals(full, dummyFedFactory.getFullSyncCounter());
        Assert.assertTrue("Assertion failed. newChanged=" + newChanged + ", changed=" + changed, newChanged > (changed + 1));
        // Assert that dummy provider won't be invoked anymore
        sleep(1800);
        Assert.assertEquals(full, dummyFedFactory.getFullSyncCounter());
        int newestChanged = dummyFedFactory.getChangedSyncCounter();
        Assert.assertEquals("Assertion failed. newChanged=" + newChanged + ", newestChanged=" + newestChanged, newChanged, newestChanged);
    });
    // remove dummyProvider
    testingClient.server().run(session -> {
        RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST);
        UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm);
        appRealm.removeComponent(dummyModel);
    });
}
Also used : UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) HashMap(java.util.HashMap) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) DummyUserFederationProviderFactory(org.keycloak.testsuite.federation.DummyUserFederationProviderFactory) RealmModel(org.keycloak.models.RealmModel) UserStorageProvider(org.keycloak.storage.UserStorageProvider) ComponentModel(org.keycloak.component.ComponentModel) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) Test(org.junit.Test) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest)

Example 9 with KeycloakSessionFactory

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

the class SyncFederationTest method test02PeriodicSyncOnUpdate.

/**
 * Test that period sync is triggered when updating a synchronized User Storage Provider to have a non-negative sync period
 */
@Test
public void test02PeriodicSyncOnUpdate() {
    final Map<String, Integer> state = testingClient.server().fetch(session -> {
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        DummyUserFederationProviderFactory dummyFedFactory = (DummyUserFederationProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, DummyUserFederationProviderFactory.PROVIDER_NAME);
        int full = dummyFedFactory.getFullSyncCounter();
        int changed = dummyFedFactory.getChangedSyncCounter();
        Map<String, Integer> state1 = new HashMap<>();
        state1.put("full", full);
        state1.put("changed", changed);
        return state1;
    }, Map.class);
    // Configure sync without timer for SyncDummyUserFederationProvider
    testingClient.server().run(session -> {
        RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST);
        UserStorageProviderModel model = new UserStorageProviderModel();
        model.setProviderId(DummyUserFederationProviderFactory.PROVIDER_NAME);
        model.setPriority(1);
        model.setName("test-sync-dummy");
        model.setFullSyncPeriod(-1);
        model.setChangedSyncPeriod(-1);
        model.setLastSync(0);
        ComponentModel dummyModel = new UserStorageProviderModel(appRealm.addComponentModel(model));
    });
    testingClient.server().run(session -> {
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        DummyUserFederationProviderFactory dummyFedFactory = (DummyUserFederationProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, DummyUserFederationProviderFactory.PROVIDER_NAME);
        // Assert that after some period was DummyUserFederationProvider triggered
        UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
        // Assert that dummy provider wasn't invoked anymore
        sleep(1800);
        int full = state.get("full");
        int changed = state.get("changed");
        Assert.assertEquals(full, dummyFedFactory.getFullSyncCounter());
        int newChanged = dummyFedFactory.getChangedSyncCounter();
        Assert.assertEquals("Assertion failed. changed=" + changed + ", newChanged=" + newChanged, changed, newChanged);
    });
    // Re-enable periodic sync for changed users
    testingClient.server().run(session -> {
        RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST);
        UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm);
        dummyModel.setChangedSyncPeriod(1);
        appRealm.updateComponent(dummyModel);
    });
    testingClient.server().run(session -> {
        RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST);
        UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm);
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        DummyUserFederationProviderFactory dummyFedFactory = (DummyUserFederationProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, DummyUserFederationProviderFactory.PROVIDER_NAME);
        // Assert that after some period was DummyUserFederationProvider triggered
        UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
        sleep(1800);
        // Cancel timer
        usersSyncManager.notifyToRefreshPeriodicSync(session, appRealm, dummyModel, true);
        log.infof("Notified sync manager about cancel periodic sync");
        // This sync is here just to ensure that we have lock (doublecheck that periodic sync, which was possibly triggered before canceling timer is finished too)
        while (true) {
            SynchronizationResult result = usersSyncManager.syncChangedUsers(session.getKeycloakSessionFactory(), appRealm.getId(), dummyModel);
            if (result.isIgnored()) {
                log.infof("Still waiting for lock before periodic sync is finished", result.toString());
                sleep(1000);
            } else {
                break;
            }
        }
        int full = state.get("full");
        int changed = state.get("changed");
        // Assert that DummyUserFederationProviderFactory.syncChangedUsers was invoked at least 1 time
        int newChanged = dummyFedFactory.getChangedSyncCounter();
        Assert.assertEquals(full, dummyFedFactory.getFullSyncCounter());
        log.info("Asserting. newChanged=" + newChanged + " > changed=" + changed);
        Assert.assertTrue("Assertion failed. newChanged=" + newChanged + ", changed=" + changed, newChanged > (changed + 1));
        // Assert that dummy provider won't be invoked anymore
        sleep(1800);
        Assert.assertEquals(full, dummyFedFactory.getFullSyncCounter());
        int newestChanged = dummyFedFactory.getChangedSyncCounter();
        Assert.assertEquals("Assertion failed. newChanged=" + newChanged + ", newestChanged=" + newestChanged, newChanged, newestChanged);
    });
    // remove dummyProvider
    testingClient.server().run(session -> {
        RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST);
        UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm);
        appRealm.removeComponent(dummyModel);
    });
}
Also used : UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) HashMap(java.util.HashMap) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) DummyUserFederationProviderFactory(org.keycloak.testsuite.federation.DummyUserFederationProviderFactory) RealmModel(org.keycloak.models.RealmModel) UserStorageProvider(org.keycloak.storage.UserStorageProvider) ComponentModel(org.keycloak.component.ComponentModel) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) Test(org.junit.Test) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest)

Example 10 with KeycloakSessionFactory

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

the class DefaultInfinispanConnectionProviderFactory method registerSystemWideListeners.

private void registerSystemWideListeners(KeycloakSession session) {
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    ClusterProvider cluster = session.getProvider(ClusterProvider.class);
    cluster.registerListener(REALM_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> {
        if (event instanceof ClearCacheEvent) {
            sessionFactory.invalidate(ObjectType._ALL_);
        }
    });
    cluster.registerListener(REALM_INVALIDATION_EVENTS, (ClusterEvent event) -> {
        if (event instanceof RealmUpdatedEvent) {
            RealmUpdatedEvent rr = (RealmUpdatedEvent) event;
            sessionFactory.invalidate(ObjectType.REALM, rr.getId());
        } else if (event instanceof RealmRemovedEvent) {
            RealmRemovedEvent rr = (RealmRemovedEvent) event;
            sessionFactory.invalidate(ObjectType.REALM, rr.getId());
        }
    });
}
Also used : ClusterEvent(org.keycloak.cluster.ClusterEvent) ClearCacheEvent(org.keycloak.models.cache.infinispan.ClearCacheEvent) ClusterProvider(org.keycloak.cluster.ClusterProvider) RealmRemovedEvent(org.keycloak.models.cache.infinispan.events.RealmRemovedEvent) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) RealmUpdatedEvent(org.keycloak.models.cache.infinispan.events.RealmUpdatedEvent)

Aggregations

KeycloakSessionFactory (org.keycloak.models.KeycloakSessionFactory)33 KeycloakSession (org.keycloak.models.KeycloakSession)11 RealmModel (org.keycloak.models.RealmModel)11 Test (org.junit.Test)10 UserModel (org.keycloak.models.UserModel)9 SynchronizationResult (org.keycloak.storage.user.SynchronizationResult)9 UserStorageSyncManager (org.keycloak.services.managers.UserStorageSyncManager)8 ComponentModel (org.keycloak.component.ComponentModel)7 IdentityProviderMapper (org.keycloak.broker.provider.IdentityProviderMapper)5 ClusterProvider (org.keycloak.cluster.ClusterProvider)5 FederatedIdentityModel (org.keycloak.models.FederatedIdentityModel)5 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)5 HashMap (java.util.HashMap)4 Logger (org.jboss.logging.Logger)4 KeycloakModelUtils (org.keycloak.models.utils.KeycloakModelUtils)4 UserStorageProviderModel (org.keycloak.storage.UserStorageProviderModel)4 Arrays (java.util.Arrays)3 LinkedList (java.util.LinkedList)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 Function (java.util.function.Function)3