Search in sources :

Example 26 with KeycloakSessionFactory

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

the class IdentityBrokerService method updateFederatedIdentity.

private void updateFederatedIdentity(BrokeredIdentityContext context, UserModel federatedUser) {
    FederatedIdentityModel federatedIdentityModel = this.session.users().getFederatedIdentity(this.realmModel, federatedUser, context.getIdpConfig().getAlias());
    if (context.getIdpConfig().getSyncMode() == IdentityProviderSyncMode.FORCE) {
        setBasicUserAttributes(context, federatedUser);
    }
    // Skip DB write if tokens are null or equal
    updateToken(context, federatedUser, federatedIdentityModel);
    context.getIdp().updateBrokeredUser(session, realmModel, federatedUser, context);
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    realmModel.getIdentityProviderMappersByAliasStream(context.getIdpConfig().getAlias()).forEach(mapper -> {
        IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
        IdentityProviderMapperSyncModeDelegate.delegateUpdateBrokeredUser(session, realmModel, federatedUser, mapper, context, target);
    });
}
Also used : FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory)

Example 27 with KeycloakSessionFactory

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

the class IdentityBrokerService method afterFirstBrokerLogin.

private Response afterFirstBrokerLogin(AuthenticationSessionModel authSession) {
    try {
        this.event.detail(Details.CODE_ID, authSession.getParentSession().getId()).removeDetail("auth_method");
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        if (serializedCtx == null) {
            throw new IdentityBrokerException("Not found serialized context in clientSession");
        }
        BrokeredIdentityContext context = serializedCtx.deserialize(session, authSession);
        String providerId = context.getIdpConfig().getAlias();
        event.detail(Details.IDENTITY_PROVIDER, providerId);
        event.detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
        // Ensure the first-broker-login flow was successfully finished
        String authProvider = authSession.getAuthNote(AbstractIdpAuthenticator.FIRST_BROKER_LOGIN_SUCCESS);
        if (authProvider == null || !authProvider.equals(providerId)) {
            throw new IdentityBrokerException("Invalid request. Not found the flag that first-broker-login flow was finished");
        }
        // firstBrokerLogin workflow finished. Removing note now
        authSession.removeAuthNote(AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        UserModel federatedUser = authSession.getAuthenticatedUser();
        if (federatedUser == null) {
            throw new IdentityBrokerException("Couldn't found authenticated federatedUser in authentication session");
        }
        event.user(federatedUser);
        event.detail(Details.USERNAME, federatedUser.getUsername());
        if (context.getIdpConfig().isAddReadTokenRoleOnCreate()) {
            ClientModel brokerClient = realmModel.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
            if (brokerClient == null) {
                throw new IdentityBrokerException("Client 'broker' not available. Maybe realm has not migrated to support the broker token exchange service");
            }
            RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE);
            federatedUser.grantRole(readTokenRole);
        }
        // Add federated identity link here
        FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(context.getIdpConfig().getAlias(), context.getId(), context.getUsername(), context.getToken());
        session.users().addFederatedIdentity(realmModel, federatedUser, federatedIdentityModel);
        String isRegisteredNewUser = authSession.getAuthNote(AbstractIdpAuthenticator.BROKER_REGISTERED_NEW_USER);
        if (Boolean.parseBoolean(isRegisteredNewUser)) {
            logger.debugf("Registered new user '%s' after first login with identity provider '%s'. Identity provider username is '%s' . ", federatedUser.getUsername(), providerId, context.getUsername());
            context.getIdp().importNewUser(session, realmModel, federatedUser, context);
            KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
            realmModel.getIdentityProviderMappersByAliasStream(providerId).forEach(mapper -> {
                IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
                target.importNewUser(session, realmModel, federatedUser, mapper, context);
            });
            if (context.getIdpConfig().isTrustEmail() && !Validation.isBlank(federatedUser.getEmail()) && !Boolean.parseBoolean(authSession.getAuthNote(AbstractIdpAuthenticator.UPDATE_PROFILE_EMAIL_CHANGED))) {
                logger.debugf("Email verified automatically after registration of user '%s' through Identity provider '%s' ", federatedUser.getUsername(), context.getIdpConfig().getAlias());
                federatedUser.setEmailVerified(true);
            }
            event.event(EventType.REGISTER).detail(Details.REGISTER_METHOD, "broker").detail(Details.EMAIL, federatedUser.getEmail()).success();
        } else {
            logger.debugf("Linked existing keycloak user '%s' with identity provider '%s' . Identity provider username is '%s' .", federatedUser.getUsername(), providerId, context.getUsername());
            event.event(EventType.FEDERATED_IDENTITY_LINK).success();
            updateFederatedIdentity(context, federatedUser);
        }
        return finishOrRedirectToPostBrokerLogin(authSession, context, true);
    } catch (Exception e) {
        return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) RoleModel(org.keycloak.models.RoleModel) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) OAuthErrorException(org.keycloak.OAuthErrorException) NotFoundException(javax.ws.rs.NotFoundException) ErrorPageException(org.keycloak.services.ErrorPageException)

Example 28 with KeycloakSessionFactory

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

the class InfinispanAuthenticationSessionProviderFactory method registerClusterListeners.

protected void registerClusterListeners(KeycloakSession session) {
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    ClusterProvider cluster = session.getProvider(ClusterProvider.class);
    cluster.registerListener(REALM_REMOVED_AUTHSESSION_EVENT, new AbstractAuthSessionClusterListener<RealmRemovedSessionEvent>(sessionFactory) {

        @Override
        protected void eventReceived(KeycloakSession session, InfinispanAuthenticationSessionProvider provider, RealmRemovedSessionEvent sessionEvent) {
            provider.onRealmRemovedEvent(sessionEvent.getRealmId());
        }
    });
    cluster.registerListener(CLIENT_REMOVED_AUTHSESSION_EVENT, new AbstractAuthSessionClusterListener<ClientRemovedSessionEvent>(sessionFactory) {

        @Override
        protected void eventReceived(KeycloakSession session, InfinispanAuthenticationSessionProvider provider, ClientRemovedSessionEvent sessionEvent) {
            provider.onClientRemovedEvent(sessionEvent.getRealmId(), sessionEvent.getClientUuid());
        }
    });
    log.debug("Registered cluster listeners");
}
Also used : ClusterProvider(org.keycloak.cluster.ClusterProvider) KeycloakSession(org.keycloak.models.KeycloakSession) ClientRemovedSessionEvent(org.keycloak.models.sessions.infinispan.events.ClientRemovedSessionEvent) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) RealmRemovedSessionEvent(org.keycloak.models.sessions.infinispan.events.RealmRemovedSessionEvent)

Example 29 with KeycloakSessionFactory

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

the class KeycloakModelTest method closeKeycloakSessionFactory.

public static synchronized void closeKeycloakSessionFactory() {
    KeycloakSessionFactory f = getFactory();
    setFactory(null);
    if (f != null) {
        LOG.debugf("Closing %s", f);
        f.close();
    }
}
Also used : KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) DefaultKeycloakSessionFactory(org.keycloak.services.DefaultKeycloakSessionFactory)

Example 30 with KeycloakSessionFactory

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

the class DBLockTest method testLockConcurrentlyInternal.

private void testLockConcurrentlyInternal(KeycloakSession sessionLC, DBLockProvider.Namespace lock) {
    long startupTime = System.currentTimeMillis();
    final Semaphore semaphore = new Semaphore();
    final KeycloakSessionFactory sessionFactory = sessionLC.getKeycloakSessionFactory();
    List<Thread> threads = new LinkedList<>();
    for (int i = 0; i < THREADS_COUNT; i++) {
        Thread thread = new Thread(() -> {
            for (int j = 0; j < ITERATIONS_PER_THREAD; j++) {
                try {
                    KeycloakModelUtils.runJobInTransaction(sessionFactory, session1 -> lock(session1, lock, semaphore));
                } catch (RuntimeException e) {
                    semaphore.setException(e);
                    throw e;
                }
            }
        });
        threads.add(thread);
    }
    for (Thread thread : threads) {
        thread.start();
    }
    for (Thread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    long took = (System.currentTimeMillis() - startupTime);
    log.infof("DBLockTest executed in %d ms with total counter %d. THREADS_COUNT=%d, ITERATIONS_PER_THREAD=%d", took, semaphore.getTotal(), THREADS_COUNT, ITERATIONS_PER_THREAD);
    Assert.assertEquals(THREADS_COUNT * ITERATIONS_PER_THREAD, semaphore.getTotal());
    Assert.assertNull(semaphore.getException());
}
Also used : KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) LinkedList(java.util.LinkedList)

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