org.keycloak.models.KeycloakSessionFactory Java Examples

The following examples show how to use org.keycloak.models.KeycloakSessionFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SingleFileImportProvider.java    From keycloak-export with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void importModel(KeycloakSessionFactory factory, Strategy strategy) throws IOException {
    logger.infof("Full importing from file %s", this.file.getAbsolutePath());

    BetterRealmRepresentation masterRealm = getMasterRealm();
    KeycloakModelUtils.runJobInTransaction(factory, session -> {
        // Import master realm first, if exists
        if (masterRealm != null) {
            importRealm(session, masterRealm, strategy);
        }
        realmReps.stream().filter(r -> r != masterRealm).forEach(r -> importRealm(session, r, strategy));

        if (masterRealm != null) {
            // If master was imported, we may need to re-create realm management clients
            for (RealmModel realm : session.realms().getRealms()) {
                if (realm.getMasterAdminClient() == null) {
                    logger.infof("Re-created management client in master realm for realm '%s'", realm.getName());
                    new RealmManager(session).setupMasterAdminManagement(realm);
                }
            }
        }
    });
}
 
Example #2
Source File: InfinispanPublicKeyStorageProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
    factory.register(new ProviderEventListener() {

        @Override
        public void onEvent(ProviderEvent event) {
            if (keysCache == null) {
                return;
            }

            SessionAndKeyHolder cacheKey = getCacheKeyToInvalidate(event);
            if (cacheKey != null) {
                log.debugf("Invalidating %s from keysCache", cacheKey);
                InfinispanPublicKeyStorageProvider provider = (InfinispanPublicKeyStorageProvider) cacheKey.session.getProvider(PublicKeyStorageProvider.class, getId());
                for (String ck : cacheKey.cacheKeys) provider.addInvalidation(ck);
            }
        }

    });
}
 
Example #3
Source File: AuthorizationStoreFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
default void registerSynchronizationListeners(KeycloakSessionFactory factory) {
    Map<Class<? extends ProviderEvent>, Synchronizer> synchronizers = new HashMap<>();

    synchronizers.put(ClientRemovedEvent.class, new ClientApplicationSynchronizer());
    synchronizers.put(RealmRemovedEvent.class, new RealmSynchronizer());
    synchronizers.put(UserRemovedEvent.class, new UserSynchronizer());
    synchronizers.put(GroupModel.GroupRemovedEvent.class, new GroupSynchronizer());

    factory.register(event -> {
        try {
            synchronizers.forEach((eventType, synchronizer) -> {
                if (eventType.isInstance(event)) {
                    synchronizer.synchronize(event, factory);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException("Error synchronizing authorization data.", e);
        }
    });
}
 
Example #4
Source File: LDAPStorageProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void syncMappers(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel model) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            RealmModel realm = session.realms().getRealm(realmId);
            session.getContext().setRealm(realm);
            session.getProvider(UserStorageProvider.class, model);
            List<ComponentModel> mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
            for (ComponentModel mapperModel : mappers) {
                LDAPStorageMapper ldapMapper = session.getProvider(LDAPStorageMapper.class, mapperModel);
                SynchronizationResult syncResult = ldapMapper.syncDataFromFederationProviderToKeycloak(realm);
                if (syncResult.getAdded() > 0 || syncResult.getUpdated() > 0 || syncResult.getRemoved() > 0 || syncResult.getFailed() > 0) {
                    logger.infof("Sync of federation mapper '%s' finished. Status: %s", mapperModel.getName(), syncResult.toString());
                }
            }
        }

    });
}
 
Example #5
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void updateFederatedIdentity(BrokeredIdentityContext context, UserModel federatedUser) {
    FederatedIdentityModel federatedIdentityModel = this.session.users().getFederatedIdentity(federatedUser, context.getIdpConfig().getAlias(), this.realmModel);

    // Skip DB write if tokens are null or equal
    updateToken(context, federatedUser, federatedIdentityModel);
    context.getIdp().updateBrokeredUser(session, realmModel, federatedUser, context);
    Set<IdentityProviderMapperModel> mappers = realmModel.getIdentityProviderMappersByAlias(context.getIdpConfig().getAlias());
    if (mappers != null) {
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        for (IdentityProviderMapperModel mapper : mappers) {
            IdentityProviderMapper target = (IdentityProviderMapper)sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
            IdentityProviderMapperSyncModeDelegate.delegateUpdateBrokeredUser(session, realmModel, federatedUser, mapper, context, target);
        }
    }

}
 
Example #6
Source File: TestPlatform.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(Runnable startupHook) {
    startupHook.run();
    KeycloakApplication keycloakApplication = Resteasy.getContextData(KeycloakApplication.class);
    ServletContext context = Resteasy.getContextData(ServletContext.class);
    context.setAttribute(KeycloakSessionFactory.class.getName(),  keycloakApplication.getSessionFactory());
}
 
Example #7
Source File: JtaTransactionWrapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public JtaTransactionWrapper(KeycloakSessionFactory factory, TransactionManager tm) {
    this.tm = tm;
    this.factory = factory;
    try {

        suspended = tm.suspend();
        logger.debug("new JtaTransactionWrapper");
        logger.debugv("was existing? {0}", suspended != null);
        tm.begin();
        ut = tm.getTransaction();
        //ended = new Exception();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: LDAPStorageProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public SynchronizationResult sync(KeycloakSessionFactory sessionFactory, String realmId, UserStorageProviderModel model) {
    syncMappers(sessionFactory, realmId, model);

    logger.infof("Sync all users from LDAP to local store: realm: %s, federation provider: %s", realmId, model.getName());

    try (LDAPQuery userQuery = createQuery(sessionFactory, realmId, model)) {
        SynchronizationResult syncResult = syncImpl(sessionFactory, userQuery, realmId, model);

        // TODO: Remove all existing keycloak users, which have federation links, but are not in LDAP. Perhaps don't check users, which were just added or updated during this sync?

        logger.infof("Sync all users finished: %s", syncResult.getStatus());
        return syncResult;
    }
}
 
Example #9
Source File: KeycloakApplication.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setupScheduledTasks(final KeycloakSessionFactory sessionFactory) {
    long interval = Config.scope("scheduled").getLong("interval", 900L) * 1000;

    KeycloakSession session = sessionFactory.create();
    try {
        TimerProvider timer = session.getProvider(TimerProvider.class);
        timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredEvents(), interval), interval, "ClearExpiredEvents");
        timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredClientInitialAccessTokens(), interval), interval, "ClearExpiredClientInitialAccessTokens");
        timer.schedule(new ScheduledTaskRunner(sessionFactory, new ClearExpiredUserSessions()), interval, ClearExpiredUserSessions.TASK_NAME);
        new UserStorageSyncManager().bootstrapPeriodic(sessionFactory, timer);
    } finally {
        session.close();
    }
}
 
Example #10
Source File: MgmtPermissions.java    From keycloak with Apache License 2.0 5 votes vote down vote up
MgmtPermissions(KeycloakSession session, RealmModel realm) {
    this.session = session;
    this.realm = realm;
    KeycloakSessionFactory keycloakSessionFactory = session.getKeycloakSessionFactory();
    AuthorizationProviderFactory factory = (AuthorizationProviderFactory) keycloakSessionFactory.getProviderFactory(AuthorizationProvider.class);
    this.authz = factory.create(session, realm);
}
 
Example #11
Source File: InfinispanCacheInitializer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void initCache() {
    final ComponentRegistry cr = this.workCache.getAdvancedCache().getComponentRegistry();
    try {
        cr.registerComponent(sessionFactory, KeycloakSessionFactory.class);
    } catch (UnsupportedOperationException | CacheConfigurationException ex) {
        if (cr.getComponent(KeycloakSessionFactory.class) != sessionFactory) {
            throw ex;
        }
    }
}
 
Example #12
Source File: UserStorageSyncManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public SynchronizationResult syncAllUsers(final KeycloakSessionFactory sessionFactory, final String realmId, final UserStorageProviderModel provider) {
    UserStorageProviderFactory factory = (UserStorageProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, provider.getProviderId());
    if (!(factory instanceof ImportSynchronization) || !provider.isImportEnabled() || !provider.isEnabled()) {
        return SynchronizationResult.ignored();

    }

    final Holder holder = new Holder();

    // Ensure not executed concurrently on this or any other cluster node
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
            // shared key for "full" and "changed" . Improve if needed
            String taskKey = provider.getId() + "::sync";

            // 30 seconds minimal timeout for now
            int timeout = Math.max(30, provider.getFullSyncPeriod());
            holder.result = clusterProvider.executeIfNotExecuted(taskKey, timeout, new Callable<SynchronizationResult>() {

                @Override
                public SynchronizationResult call() throws Exception {
                    updateLastSyncInterval(sessionFactory, provider, realmId);
                    return ((ImportSynchronization)factory).sync(sessionFactory, realmId, provider);
                }

            });
        }

    });

    if (holder.result == null || !holder.result.isExecuted()) {
        logger.debugf("syncAllUsers for federation provider %s was ignored as it's already in progress", provider.getName());
        return SynchronizationResult.ignored();
    } else {
        return holder.result.getResult();
    }
}
 
Example #13
Source File: SingleFileImportProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void importModel(KeycloakSessionFactory factory, final Strategy strategy) throws IOException {
    logger.infof("Full importing from file %s", this.file.getAbsolutePath());
    checkRealmReps();

    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            ImportUtils.importRealms(session, realmReps.values(), strategy);
        }

    });
}
 
Example #14
Source File: GroupSynchronizer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void synchronize(GroupModel.GroupRemovedEvent event, KeycloakSessionFactory factory) {
    ProviderFactory<AuthorizationProvider> providerFactory = factory.getProviderFactory(AuthorizationProvider.class);
    AuthorizationProvider authorizationProvider = providerFactory.create(event.getKeycloakSession());

    StoreFactory storeFactory = authorizationProvider.getStoreFactory();
    PolicyStore policyStore = storeFactory.getPolicyStore();
    GroupModel group = event.getGroup();
    Map<String, String[]> attributes = new HashMap<>();

    attributes.put("type", new String[] {"group"});
    attributes.put("config:groups", new String[] {group.getId()});

    List<Policy> search = policyStore.findByResourceServer(attributes, null, -1, -1);

    for (Policy policy : search) {
        PolicyProviderFactory policyFactory = authorizationProvider.getProviderFactory(policy.getType());
        GroupPolicyRepresentation representation = GroupPolicyRepresentation.class.cast(policyFactory.toRepresentation(policy, authorizationProvider));
        Set<GroupPolicyRepresentation.GroupDefinition> groups = representation.getGroups();

        groups.removeIf(groupDefinition -> groupDefinition.getId().equals(group.getId()));

        if (groups.isEmpty()) {
            policyFactory.onRemove(policy, authorizationProvider);
            policyStore.delete(policy.getId());
        } else {
            policyFactory.onUpdate(policy, representation, authorizationProvider);
        }
    }
}
 
Example #15
Source File: SingleFileExportProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void exportRealm(KeycloakSessionFactory factory, final String realmName) throws IOException {
    logger.infof("Exporting realm '%s' into file %s", realmName, this.file.getAbsolutePath());
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            RealmModel realm = session.realms().getRealmByName(realmName);
            RealmRepresentation realmRep = ExportUtils.exportRealm(session, realm, true, true);
            writeToFile(realmRep);
        }

    });
}
 
Example #16
Source File: NotUsernamePasswordPolicyProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #17
Source File: RemoteUserFederationProviderFactory.java    From keycloak-user-migration-provider with Apache License 2.0 4 votes vote down vote up
@Override
public UserFederationSyncResult syncAllUsers(KeycloakSessionFactory sessionFactory, String realmId, UserFederationProviderModel model)
{
    throw new UnsupportedOperationException("This federation provider doesn't support syncAllUsers()");
}
 
Example #18
Source File: MetricsEndpointFactory.java    From keycloak-metrics-spi with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
    // nothing to do
}
 
Example #19
Source File: DigitsPasswordPolicyProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #20
Source File: UpperCasePasswordPolicyProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #21
Source File: DummyUserFederationProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public SynchronizationResult syncSince(Date lastSync, KeycloakSessionFactory sessionFactory, String realmId, UserStorageProviderModel model) {
    logger.info("syncChangedUsers invoked");
    changedSyncCounter.incrementAndGet();
    return SynchronizationResult.empty();
}
 
Example #22
Source File: HashIterationsPasswordPolicyProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #23
Source File: QuarkusJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
    this.factory = factory;
    checkJtaEnabled(factory);
    lazyInit();
}
 
Example #24
Source File: DefaultEmailSenderProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #25
Source File: DefaultPasswordPolicyManagerProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #26
Source File: KeycloakApplication.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public KeycloakSessionFactory getSessionFactory() {
    return sessionFactory;
}
 
Example #27
Source File: OIDCClientDescriptionConverterFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #28
Source File: DefaultAuthorizationProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #29
Source File: EventsListenerProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
}
 
Example #30
Source File: DefaultKeycloakSession.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public KeycloakSessionFactory getKeycloakSessionFactory() {
    return factory;
}