Search in sources :

Example 6 with ProviderFactory

use of org.keycloak.provider.ProviderFactory in project keycloak by keycloak.

the class DefaultKeycloakSessionFactory method checkProvider.

protected void checkProvider() {
    // make sure to recreated the default providers map
    provider.clear();
    for (Spi spi : spis) {
        String defaultProvider = Config.getProvider(spi.getName());
        if (defaultProvider != null) {
            if (getProviderFactory(spi.getProviderClass(), defaultProvider) == null) {
                throw new RuntimeException("Failed to find provider " + defaultProvider + " for " + spi.getName());
            }
        } else {
            Map<String, ProviderFactory> factories = factoriesMap.get(spi.getProviderClass());
            if (factories != null && factories.size() == 1) {
                defaultProvider = factories.values().iterator().next().getId();
            }
            if (defaultProvider == null) {
                Optional<ProviderFactory> highestPriority = factories.values().stream().max(Comparator.comparing(ProviderFactory::order));
                if (highestPriority.isPresent() && highestPriority.get().order() > 0) {
                    defaultProvider = highestPriority.get().getId();
                }
            }
            if (defaultProvider == null && factories.containsKey("default")) {
                defaultProvider = "default";
            }
        }
        if (defaultProvider != null) {
            this.provider.put(spi.getProviderClass(), defaultProvider);
            logger.debugv("Set default provider for {0} to {1}", spi.getName(), defaultProvider);
        } else {
            logger.debugv("No default provider for {0}", spi.getName());
        }
    }
}
Also used : EnvironmentDependentProviderFactory(org.keycloak.provider.EnvironmentDependentProviderFactory) ComponentFactoryProviderFactory(org.keycloak.component.ComponentFactoryProviderFactory) ProviderFactory(org.keycloak.provider.ProviderFactory) Spi(org.keycloak.provider.Spi)

Example 7 with ProviderFactory

use of org.keycloak.provider.ProviderFactory in project keycloak by keycloak.

the class ClientRegistrationPolicyResource method getProviders.

/**
 * Base path for retrieve providers with the configProperties properly filled
 *
 * @return
 */
@Path("providers")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Stream<ComponentTypeRepresentation> getProviders() {
    return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientRegistrationPolicy.class).map((ProviderFactory factory) -> {
        ClientRegistrationPolicyFactory clientRegFactory = (ClientRegistrationPolicyFactory) factory;
        List<ProviderConfigProperty> configProps = clientRegFactory.getConfigProperties(session);
        ComponentTypeRepresentation rep = new ComponentTypeRepresentation();
        rep.setId(clientRegFactory.getId());
        rep.setHelpText(clientRegFactory.getHelpText());
        rep.setProperties(ModelToRepresentation.toRepresentation(configProps));
        return rep;
    });
}
Also used : ClientRegistrationPolicy(org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy) ComponentTypeRepresentation(org.keycloak.representations.idm.ComponentTypeRepresentation) ProviderFactory(org.keycloak.provider.ProviderFactory) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) ClientRegistrationPolicyFactory(org.keycloak.services.clientregistration.policy.ClientRegistrationPolicyFactory) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 8 with ProviderFactory

use of org.keycloak.provider.ProviderFactory in project keycloak by keycloak.

the class KeycloakModelTest method createKeycloakSessionFactory.

/**
 * Creates a fresh initialized {@link KeycloakSessionFactory}. The returned factory uses configuration
 * local to the thread that calls this method, allowing for per-thread customization. This in turn allows
 * testing of several parallel session factories which can be used to simulate several servers
 * running in parallel.
 * @return
 */
public static KeycloakSessionFactory createKeycloakSessionFactory() {
    int factoryIndex = FACTORY_COUNT.incrementAndGet();
    String threadName = Thread.currentThread().getName();
    CONFIG.reset();
    CONFIG.spi(ComponentFactorySpi.NAME).provider(DefaultComponentFactoryProviderFactory.PROVIDER_ID).config("cachingForced", "true");
    MODEL_PARAMETERS.forEach(m -> m.updateConfig(CONFIG));
    LOG.debugf("Creating factory %d in %s using the following configuration:\n    %s", factoryIndex, threadName, CONFIG);
    DefaultKeycloakSessionFactory res = new DefaultKeycloakSessionFactory() {

        @Override
        protected boolean isEnabled(ProviderFactory factory, Scope scope) {
            return super.isEnabled(factory, scope) && isFactoryAllowed(factory);
        }

        @Override
        protected Map<Class<? extends Provider>, Map<String, ProviderFactory>> loadFactories(ProviderManager pm) {
            spis.removeIf(s -> !isSpiAllowed(s));
            return super.loadFactories(pm);
        }

        private boolean isSpiAllowed(Spi s) {
            return MODEL_PARAMETERS.stream().anyMatch(p -> p.isSpiAllowed(s));
        }

        private boolean isFactoryAllowed(ProviderFactory factory) {
            return MODEL_PARAMETERS.stream().anyMatch(p -> p.isFactoryAllowed(factory));
        }

        @Override
        public String toString() {
            return "KeycloakSessionFactory " + factoryIndex + " (from " + threadName + " thread)";
        }
    };
    res.init();
    res.publish(new PostMigrationEvent());
    return res;
}
Also used : DefaultKeycloakSessionFactory(org.keycloak.services.DefaultKeycloakSessionFactory) Scope(org.keycloak.Config.Scope) DefaultExecutorsProviderFactory(org.keycloak.executors.DefaultExecutorsProviderFactory) ComponentFactoryProviderFactory(org.keycloak.component.ComponentFactoryProviderFactory) DefaultAuthorizationProviderFactory(org.keycloak.authorization.DefaultAuthorizationProviderFactory) DefaultComponentFactoryProviderFactory(org.keycloak.services.DefaultComponentFactoryProviderFactory) ProviderFactory(org.keycloak.provider.ProviderFactory) DeploymentStateProviderFactory(org.keycloak.models.DeploymentStateProviderFactory) ProviderManager(org.keycloak.provider.ProviderManager) BeforeClass(org.junit.BeforeClass) Map(java.util.Map) ComponentFactorySpi(org.keycloak.component.ComponentFactorySpi) ClientScopeSpi(org.keycloak.models.ClientScopeSpi) ExecutorsSpi(org.keycloak.executors.ExecutorsSpi) DBLockSpi(org.keycloak.models.dblock.DBLockSpi) ClusterSpi(org.keycloak.cluster.ClusterSpi) UserSpi(org.keycloak.models.UserSpi) Spi(org.keycloak.provider.Spi) UserLoginFailureSpi(org.keycloak.models.UserLoginFailureSpi) TimerSpi(org.keycloak.timer.TimerSpi) ClientSpi(org.keycloak.models.ClientSpi) StoreFactorySpi(org.keycloak.authorization.store.StoreFactorySpi) RealmSpi(org.keycloak.models.RealmSpi) GroupSpi(org.keycloak.models.GroupSpi) UserSessionSpi(org.keycloak.models.UserSessionSpi) DeploymentStateSpi(org.keycloak.models.DeploymentStateSpi) EventStoreSpi(org.keycloak.events.EventStoreSpi) AuthorizationSpi(org.keycloak.authorization.AuthorizationSpi) RoleSpi(org.keycloak.models.RoleSpi) Provider(org.keycloak.provider.Provider) PostMigrationEvent(org.keycloak.models.utils.PostMigrationEvent)

Example 9 with ProviderFactory

use of org.keycloak.provider.ProviderFactory in project keycloak by keycloak.

the class UserResource method updateUserFromRep.

public static void updateUserFromRep(UserProfile profile, UserModel user, UserRepresentation rep, KeycloakSession session, boolean isUpdateExistingUser) {
    boolean removeMissingRequiredActions = isUpdateExistingUser;
    if (rep.isEnabled() != null)
        user.setEnabled(rep.isEnabled());
    if (rep.isEmailVerified() != null)
        user.setEmailVerified(rep.isEmailVerified());
    if (rep.getFederationLink() != null)
        user.setFederationLink(rep.getFederationLink());
    List<String> reqActions = rep.getRequiredActions();
    if (reqActions != null) {
        session.getKeycloakSessionFactory().getProviderFactoriesStream(RequiredActionProvider.class).map(ProviderFactory::getId).distinct().forEach(action -> {
            if (reqActions.contains(action)) {
                user.addRequiredAction(action);
            } else if (removeMissingRequiredActions) {
                user.removeRequiredAction(action);
            }
        });
    }
    List<CredentialRepresentation> credentials = rep.getCredentials();
    if (credentials != null) {
        for (CredentialRepresentation credential : credentials) {
            if (CredentialRepresentation.PASSWORD.equals(credential.getType()) && credential.isTemporary() != null && credential.isTemporary()) {
                user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
            }
        }
    }
}
Also used : CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) ProviderFactory(org.keycloak.provider.ProviderFactory) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider)

Example 10 with ProviderFactory

use of org.keycloak.provider.ProviderFactory in project keycloak by keycloak.

the class AuthenticationManagementResource method addExecutionToFlow.

/**
 * Add new authentication execution to a flow
 *
 * @param flowAlias Alias of parent flow
 * @param data New execution JSON data containing 'provider' attribute
 */
@Path("/flows/{flowAlias}/executions/execution")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
public Response addExecutionToFlow(@PathParam("flowAlias") String flowAlias, Map<String, String> data) {
    auth.realm().requireManageRealm();
    AuthenticationFlowModel parentFlow = realm.getFlowByAlias(flowAlias);
    if (parentFlow == null) {
        throw new BadRequestException("Parent flow doesn't exist");
    }
    if (parentFlow.isBuiltIn()) {
        throw new BadRequestException("It is illegal to add execution to a built in flow");
    }
    String provider = data.get("provider");
    // make sure provider is one of the registered providers
    ProviderFactory f;
    if (parentFlow.getProviderId().equals(AuthenticationFlow.CLIENT_FLOW)) {
        f = session.getKeycloakSessionFactory().getProviderFactory(ClientAuthenticator.class, provider);
    } else if (parentFlow.getProviderId().equals(AuthenticationFlow.FORM_FLOW)) {
        f = session.getKeycloakSessionFactory().getProviderFactory(FormAction.class, provider);
    } else {
        f = session.getKeycloakSessionFactory().getProviderFactory(Authenticator.class, provider);
    }
    if (f == null) {
        throw new BadRequestException("No authentication provider found for id: " + provider);
    }
    AuthenticationExecutionModel execution = new AuthenticationExecutionModel();
    execution.setParentFlow(parentFlow.getId());
    ConfigurableAuthenticatorFactory conf = (ConfigurableAuthenticatorFactory) f;
    if (conf.getRequirementChoices().length == 1)
        execution.setRequirement(conf.getRequirementChoices()[0]);
    else
        execution.setRequirement(AuthenticationExecutionModel.Requirement.DISABLED);
    execution.setAuthenticatorFlow(false);
    execution.setAuthenticator(provider);
    execution.setPriority(getNextPriority(parentFlow));
    execution = realm.addAuthenticatorExecution(execution);
    data.put("id", execution.getId());
    adminEvent.operation(OperationType.CREATE).resource(ResourceType.AUTH_EXECUTION).resourcePath(session.getContext().getUri()).representation(data).success();
    String addExecutionPathSegment = UriBuilder.fromMethod(AuthenticationManagementResource.class, "addExecutionToFlow").build(parentFlow.getAlias()).getPath();
    return Response.created(session.getContext().getUri().getBaseUriBuilder().path(session.getContext().getUri().getPath().replace(addExecutionPathSegment, "")).path("executions").path(execution.getId()).build()).build();
}
Also used : AuthenticationExecutionModel(org.keycloak.models.AuthenticationExecutionModel) ProviderFactory(org.keycloak.provider.ProviderFactory) ClientAuthenticator(org.keycloak.authentication.ClientAuthenticator) ConfigurableAuthenticatorFactory(org.keycloak.authentication.ConfigurableAuthenticatorFactory) AuthenticationFlowModel(org.keycloak.models.AuthenticationFlowModel) BadRequestException(javax.ws.rs.BadRequestException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Aggregations

ProviderFactory (org.keycloak.provider.ProviderFactory)21 EnvironmentDependentProviderFactory (org.keycloak.provider.EnvironmentDependentProviderFactory)13 Spi (org.keycloak.provider.Spi)10 HashMap (java.util.HashMap)9 Map (java.util.Map)8 ComponentFactoryProviderFactory (org.keycloak.component.ComponentFactoryProviderFactory)8 Provider (org.keycloak.provider.Provider)7 KeycloakDeploymentInfo (org.keycloak.provider.KeycloakDeploymentInfo)6 ProviderManager (org.keycloak.provider.ProviderManager)6 List (java.util.List)4 Logger (org.jboss.logging.Logger)4 Config (org.keycloak.Config)4 MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)4 ComponentFactoryProvider (org.keycloak.component.ComponentFactoryProvider)4 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 URL (java.net.URL)3 ArrayList (java.util.ArrayList)3 Arrays (java.util.Arrays)3 Collection (java.util.Collection)3