Java Code Examples for org.keycloak.models.KeycloakSessionFactory#getProviderFactory()

The following examples show how to use org.keycloak.models.KeycloakSessionFactory#getProviderFactory() . 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: RealmSynchronizer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void synchronize(RealmRemovedEvent event, KeycloakSessionFactory factory) {
    ProviderFactory<AuthorizationProvider> providerFactory = factory.getProviderFactory(AuthorizationProvider.class);
    AuthorizationProvider authorizationProvider = providerFactory.create(event.getKeycloakSession());
    StoreFactory storeFactory = authorizationProvider.getStoreFactory();

    event.getRealm().getClients().forEach(clientModel -> {
        ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());

        if (resourceServer != null) {
            String id = resourceServer.getId();
            //storeFactory.getResourceStore().findByResourceServer(id).forEach(resource -> storeFactory.getResourceStore().delete(resource.getId()));
            //storeFactory.getScopeStore().findByResourceServer(id).forEach(scope -> storeFactory.getScopeStore().delete(scope.getId()));
            //storeFactory.getPolicyStore().findByResourceServer(id).forEach(scope -> storeFactory.getPolicyStore().delete(scope.getId()));
            storeFactory.getResourceServerStore().delete(id);
        }
    });
}
 
Example 2
Source File: ProtocolMapperUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static List<Map.Entry<ProtocolMapperModel, ProtocolMapper>> getSortedProtocolMappers(KeycloakSession session, ClientSessionContext ctx) {
    Set<ProtocolMapperModel> mapperModels = ctx.getProtocolMappers();
    Map<ProtocolMapperModel, ProtocolMapper> result = new HashMap<>();

    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    for (ProtocolMapperModel mapperModel : mapperModels) {
        ProtocolMapper mapper = (ProtocolMapper) sessionFactory.getProviderFactory(ProtocolMapper.class, mapperModel.getProtocolMapper());
        if (mapper == null) {
            continue;
        }

        result.put(mapperModel, mapper);
    }

    return result.entrySet()
            .stream()
            .sorted(Comparator.comparing(ProtocolMapperUtils::compare))
            .collect(Collectors.toList());
}
 
Example 3
Source File: NginxProxySslClientCertificateLookup.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**  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;
}
 
Example 4
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 5
Source File: ClientApplicationSynchronizer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void synchronize(ClientRemovedEvent event, KeycloakSessionFactory factory) {
    ProviderFactory<AuthorizationProvider> providerFactory = factory.getProviderFactory(AuthorizationProvider.class);
    AuthorizationProvider authorizationProvider = providerFactory.create(event.getKeycloakSession());

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

    removeFromUserPermissionTickets(event, authorizationProvider);
    removeUserResources(event, authorizationProvider);
    removeFromUserPolicies(event, authorizationProvider);
}
 
Example 7
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 8
Source File: DefaultJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void checkJtaEnabled(KeycloakSessionFactory factory) {
    jtaLookup = (JtaTransactionManagerLookup) factory.getProviderFactory(JtaTransactionManagerLookup.class);
    if (jtaLookup != null) {
        if (jtaLookup.getTransactionManager() != null) {
            jtaEnabled = true;
        }
    }
}
 
Example 9
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 10
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 11
Source File: JSSETruststoreConfigurator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public JSSETruststoreConfigurator(KeycloakSession session) {
    KeycloakSessionFactory factory = session.getKeycloakSessionFactory();
    TruststoreProviderFactory truststoreFactory = (TruststoreProviderFactory) factory.getProviderFactory(TruststoreProvider.class, "file");

    provider = truststoreFactory.create(session);
    if (provider != null && provider.getTruststore() == null) {
        provider = null;
    }
}
 
Example 12
Source File: QuarkusJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void checkJtaEnabled(KeycloakSessionFactory factory) {
    jtaLookup = (JtaTransactionManagerLookup) factory.getProviderFactory(JtaTransactionManagerLookup.class);
    if (jtaLookup != null) {
        if (jtaLookup.getTransactionManager() != null) {
            jtaEnabled = true;
        }
    }
}
 
Example 13
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private Response afterFirstBrokerLogin(ClientSessionCode<AuthenticationSessionModel> clientSessionCode) {
    AuthenticationSessionModel authSession = clientSessionCode.getClientSession();
    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);
            Set<IdentityProviderMapperModel> mappers = realmModel.getIdentityProviderMappersByAlias(providerId);
            if (mappers != null) {
                KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
                for (IdentityProviderMapperModel mapper : mappers) {
                    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, clientSessionCode);

    }  catch (Exception e) {
        return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
    }
}
 
Example 14
Source File: UserStorageSyncManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public SynchronizationResult syncChangedUsers(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.getChangedSyncPeriod());
            holder.result = clusterProvider.executeIfNotExecuted(taskKey, timeout, new Callable<SynchronizationResult>() {

                @Override
                public SynchronizationResult call() throws Exception {
                    // See when we did last sync.
                    int oldLastSync = provider.getLastSync();
                    updateLastSyncInterval(sessionFactory, provider, realmId);
                    return ((ImportSynchronization)factory).syncSince(Time.toDate(oldLastSync), sessionFactory, realmId, provider);
                }

            });
        }

    });

    if (holder.result == null || !holder.result.isExecuted()) {
        logger.debugf("syncChangedUsers for federation provider %s was ignored as it's already in progress", provider.getName());
        return SynchronizationResult.ignored();
    } else {
        return holder.result.getResult();
    }
}