org.keycloak.provider.ProviderFactory Java Examples

The following examples show how to use org.keycloak.provider.ProviderFactory. 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: FeatureDeployerUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static Map<ProviderFactory, Spi> getFactoriesDependentOnFeature(Map<ProviderFactory, Spi> factoriesDisabled, Map<ProviderFactory, Spi> factoriesEnabled) {
    Set<Class<? extends ProviderFactory>> disabledFactoriesClasses = factoriesDisabled.keySet().stream()
            .map(ProviderFactory::getClass)
            .collect(Collectors.toSet());

    Set<Class<? extends ProviderFactory>> enabledFactoriesClasses = factoriesEnabled.keySet().stream()
            .map(ProviderFactory::getClass)
            .collect(Collectors.toSet());

    enabledFactoriesClasses.removeAll(disabledFactoriesClasses);

    Map<ProviderFactory, Spi> newFactories = factoriesEnabled.entrySet().stream()
            .filter(entry -> enabledFactoriesClasses.contains(entry.getKey().getClass()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    return newFactories;
}
 
Example #3
Source File: FeatureDeployerUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void undeployFactoriesAfterFeatureDisabled(Profile.Feature feature) {
    ProviderManager manager = deployersCache.get(feature);
    if (manager == null) {
        // This is used if some feature is enabled by default and then disabled
        // Need to figure which provider factories were enabled after feature was enabled. Create deployer based on it and save it to the cache
        Map<ProviderFactory, Spi> factoriesBeforeDisable = initializer.remove(feature);
        Map<ProviderFactory, Spi> factoriesAfterDisable = loadEnabledEnvironmentFactories();
        Map<ProviderFactory, Spi>  factories = getFactoriesDependentOnFeature(factoriesAfterDisable, factoriesBeforeDisable);

        KeycloakDeploymentInfo di = createDeploymentInfo(factories);

        manager = new ProviderManager(di, FeatureDeployerUtil.class.getClassLoader());
        loadFactories(manager);
        deployersCache.put(feature, manager);
    }
    ProviderManagerRegistry.SINGLETON.undeploy(manager);
}
 
Example #4
Source File: RealmAdminResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Base path for importing clients under this realm.
 *
 * @return
 */
@Path("client-description-converter")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
@POST
@Produces(MediaType.APPLICATION_JSON)
public ClientRepresentation convertClientDescription(String description) {
    auth.clients().requireManage();

    if (realm == null) {
        throw new NotFoundException("Realm not found.");
    }

    for (ProviderFactory<ClientDescriptionConverter> factory : session.getKeycloakSessionFactory().getProviderFactories(ClientDescriptionConverter.class)) {
        if (((ClientDescriptionConverterFactory) factory).isSupported(description)) {
            return factory.create(session).convertToInternal(description);
        }
    }

    throw new BadRequestException("Unsupported format");
}
 
Example #5
Source File: ClientRegistrationPolicyResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Base path for retrieve providers with the configProperties properly filled
 *
 * @return
 */
@Path("providers")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<ComponentTypeRepresentation> getProviders() {
    List<ProviderFactory> providerFactories = session.getKeycloakSessionFactory().getProviderFactories(ClientRegistrationPolicy.class);

    return providerFactories.stream().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;

    }).collect(Collectors.toList());
}
 
Example #6
Source File: QuarkusKeycloakSessionFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void checkProviders(Spi spi) {
    String defaultProvider = Config.getProvider(spi.getName());

    if (defaultProvider != null) {
        if (getProviderFactory(spi.getProviderClass(), defaultProvider) == null) {
            throw new RuntimeException("Failed to find provider " + provider + " 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 (factories != null) {
            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 == 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());
    }
}
 
Example #7
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static IdentityProviderFactory getIdentityProviderFactory(KeycloakSession session, IdentityProviderModel model) {
    Map<String, IdentityProviderFactory> availableProviders = new HashMap<String, IdentityProviderFactory>();
    List<ProviderFactory> allProviders = new ArrayList<ProviderFactory>();

    allProviders.addAll(session.getKeycloakSessionFactory().getProviderFactories(IdentityProvider.class));
    allProviders.addAll(session.getKeycloakSessionFactory().getProviderFactories(SocialIdentityProvider.class));

    for (ProviderFactory providerFactory : allProviders) {
        availableProviders.put(providerFactory.getId(), (IdentityProviderFactory) providerFactory);
    }

    return availableProviders.get(model.getProviderId());
}
 
Example #8
Source File: OIDCWellKnownProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) {
    List<String> result = new LinkedList<>();
    for (ProviderFactory s : session.getKeycloakSessionFactory().getProviderFactories(ClientSignatureVerifierProvider.class)) {
        result.add(s.getId());
    }
    if (includeNone) {
        result.add("none");
    }
    return result;
}
 
Example #9
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public List<Map<String, Object>> buildProviderMetadata(List<ProviderFactory> factories) {
    List<Map<String, Object>> providers = new LinkedList<>();
    for (ProviderFactory factory : factories) {
        Map<String, Object> data = new HashMap<>();
        data.put("id", factory.getId());
        ConfigurableAuthenticatorFactory configured = (ConfigurableAuthenticatorFactory)factory;
        data.put("description", configured.getHelpText());
        data.put("displayName", configured.getDisplayType());

        providers.add(data);
    }
    return providers;
}
 
Example #10
Source File: OIDCWellKnownProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<String> getSupportedSigningAlgorithms(boolean includeNone) {
    List<String> result = new LinkedList<>();
    for (ProviderFactory s : session.getKeycloakSessionFactory().getProviderFactories(SignatureProvider.class)) {
        result.add(s.getId());
    }
    if (includeNone) {
        result.add("none");
    }
    return result;
}
 
Example #11
Source File: ProtocolMapperUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Find the builtin locale mapper.
 *
 * @param session A KeycloakSession
 * @return The builtin locale mapper.
 */
public static ProtocolMapperModel findLocaleMapper(KeycloakSession session) {
    for (ProviderFactory p : session.getKeycloakSessionFactory().getProviderFactories(LoginProtocol.class)) {
        LoginProtocolFactory factory = (LoginProtocolFactory) p;
        ProtocolMapperModel found = factory.getBuiltinMappers().get(OIDCLoginProtocolFactory.LOCALE);
        if (found != null && found.getProtocol().equals(OIDCLoginProtocol.LOGIN_PROTOCOL)) {
            return found;
        }
    }
    return null;
}
 
Example #12
Source File: OIDCWellKnownProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<String> getSupportedIdTokenEncryptionAlg(boolean includeNone) {
    List<String> result = new LinkedList<>();
    for (ProviderFactory s : session.getKeycloakSessionFactory().getProviderFactories(CekManagementProvider.class)) {
        result.add(s.getId());
    }
    if (includeNone) {
        result.add("none");
    }
    return result;
}
 
Example #13
Source File: QuarkusKeycloakSessionFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ProviderFactory lookupProviderFactory(Class<? extends ProviderFactory> factoryClazz) {
    ProviderFactory factory;

    try {
        factory = factoryClazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return factory;
}
 
Example #14
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get authenticator providers
 *
 * Returns a list of authenticator providers.
 */
@Path("/authenticator-providers")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<Map<String, Object>> getAuthenticatorProviders() {
    auth.realm().requireViewRealm();

    List<ProviderFactory> factories = session.getKeycloakSessionFactory().getProviderFactories(Authenticator.class);
    return buildProviderMetadata(factories);
}
 
Example #15
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get form providers
 *
 * Returns a list of form providers.
 */
@Path("/form-providers")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<Map<String, Object>> getFormProviders() {
    auth.realm().requireViewRealm();

    List<ProviderFactory> factories = session.getKeycloakSessionFactory().getProviderFactories(FormAuthenticator.class);
    return buildProviderMetadata(factories);
}
 
Example #16
Source File: AuthorizeClientUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ClientAuthenticatorFactory findClientAuthenticatorForOIDCAuthMethod(KeycloakSession session, String oidcAuthMethod) {
    List<ProviderFactory> providerFactories = session.getKeycloakSessionFactory().getProviderFactories(ClientAuthenticator.class);
    for (ProviderFactory factory : providerFactories) {
        ClientAuthenticatorFactory clientAuthFactory = (ClientAuthenticatorFactory) factory;
        if (clientAuthFactory.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL).contains(oidcAuthMethod)) {
            return clientAuthFactory;
        }
    }

    return null;
}
 
Example #17
Source File: ServerInfoAdminResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setIdentityProviders(ServerInfoRepresentation info) {
    info.setIdentityProviders(new LinkedList<Map<String, String>>());
    List<ProviderFactory> providerFactories = session.getKeycloakSessionFactory().getProviderFactories(IdentityProvider.class);
    setIdentityProviders(providerFactories, info.getIdentityProviders(), "User-defined");

    providerFactories = session.getKeycloakSessionFactory().getProviderFactories(SocialIdentityProvider.class);
    setIdentityProviders(providerFactories, info.getIdentityProviders(), "Social");
}
 
Example #18
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get client authenticator providers
 *
 * Returns a list of client authenticator providers.
 */
@Path("/client-authenticator-providers")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<Map<String, Object>> getClientAuthenticatorProviders() {
    auth.realm().requireViewClientAuthenticatorProviders();

    List<ProviderFactory> factories = session.getKeycloakSessionFactory().getProviderFactories(ClientAuthenticator.class);
    return buildProviderMetadata(factories);
}
 
Example #19
Source File: FeatureDeployerUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void initBeforeChangeFeature(Profile.Feature feature) {
    if (deployersCache.containsKey(feature)) return;

    // Compute which provider factories are enabled before feature is enabled (disabled)
    Map<ProviderFactory, Spi>  factoriesBefore = loadEnabledEnvironmentFactories();
    initializer.put(feature, factoriesBefore);
}
 
Example #20
Source File: DefaultKeycloakSessionFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void checkProvider() {
    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 " + provider + " 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());
        }
    }
}
 
Example #21
Source File: IdentityProvidersResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<ProviderFactory> getProviderFactories() {
    List<ProviderFactory> allProviders = new ArrayList<ProviderFactory>();

    allProviders.addAll(this.session.getKeycloakSessionFactory().getProviderFactories(IdentityProvider.class));
    allProviders.addAll(this.session.getKeycloakSessionFactory().getProviderFactories(SocialIdentityProvider.class));

    return allProviders;
}
 
Example #22
Source File: DefaultKeycloakSessionFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<ProviderFactory> getProviderFactories(Class<? extends Provider> clazz) {
    if (factoriesMap == null) return Collections.emptyList();
    List<ProviderFactory> list = new LinkedList<ProviderFactory>();
    Map<String, ProviderFactory> providerFactoryMap = factoriesMap.get(clazz);
    if (providerFactoryMap == null) return list;
    list.addAll(providerFactoryMap.values());
    return list;
}
 
Example #23
Source File: IdentityProviderResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get mapper types for identity provider
 */
@GET
@Path("mapper-types")
@NoCache
public Map<String, IdentityProviderMapperTypeRepresentation> getMapperTypes() {
    this.auth.realm().requireViewIdentityProviders();

    if (identityProviderModel == null) {
        throw new javax.ws.rs.NotFoundException();
    }

    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    Map<String, IdentityProviderMapperTypeRepresentation> types = new HashMap<>();
    List<ProviderFactory> factories = sessionFactory.getProviderFactories(IdentityProviderMapper.class);
    for (ProviderFactory factory : factories) {
        IdentityProviderMapper mapper = (IdentityProviderMapper)factory;
        for (String type : mapper.getCompatibleProviders()) {
            if (IdentityProviderMapper.ANY_PROVIDER.equals(type) || type.equals(identityProviderModel.getProviderId())) {
                IdentityProviderMapperTypeRepresentation rep = new IdentityProviderMapperTypeRepresentation();
                rep.setId(mapper.getId());
                rep.setCategory(mapper.getDisplayCategory());
                rep.setName(mapper.getDisplayType());
                rep.setHelpText(mapper.getHelpText());
                List<ProviderConfigProperty> configProperties = mapper.getConfigProperties();
                for (ProviderConfigProperty prop : configProperties) {
                    ConfigPropertyRepresentation propRep = ModelToRepresentation.toRepresentation(prop);
                    rep.getProperties().add(propRep);
                }
                types.put(rep.getId(), rep);
                break;
            }
        }
    }
    return types;
}
 
Example #24
Source File: FeatureDeployerUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static KeycloakDeploymentInfo createDeploymentInfo(Map<ProviderFactory, Spi> factories) {
    KeycloakDeploymentInfo di = KeycloakDeploymentInfo.create();
    for (Map.Entry<ProviderFactory, Spi> factory : factories.entrySet()) {
        ProviderFactory pf = factory.getKey();
        Class<? extends Spi> spiClass = factory.getValue().getClass();
        di.addProvider(spiClass, pf);
    }
    return di;
}
 
Example #25
Source File: MigrateUserFedToComponent.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    List<ProviderFactory> factories = kcSession.getKeycloakSessionFactory().getProviderFactories(UserStorageProvider.class);
    for (ProviderFactory factory : factories) {
        if (!factory.getId().equals(LDAPConstants.LDAP_PROVIDER)) {
            convertFedProviderToComponent(factory.getId(), null);
        }
    }
}
 
Example #26
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 *  Get configuration descriptions for all clients
 */
@Path("per-client-config-description")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Map<String, List<ConfigPropertyRepresentation>> getPerClientConfigDescription() {
    auth.realm().requireViewClientAuthenticatorProviders();

    List<ProviderFactory> factories = session.getKeycloakSessionFactory().getProviderFactories(ClientAuthenticator.class);

    Map<String, List<ConfigPropertyRepresentation>> toReturn = new HashMap<>();
    for (ProviderFactory clientAuthenticatorFactory : factories) {
        String providerId = clientAuthenticatorFactory.getId();
        ConfigurableAuthenticatorFactory factory = CredentialHelper.getConfigurableAuthenticatorFactory(session, providerId);
        ClientAuthenticatorFactory clientAuthFactory = (ClientAuthenticatorFactory) factory;
        List<ProviderConfigProperty> perClientConfigProps = clientAuthFactory.getConfigPropertiesPerClient();
        List<ConfigPropertyRepresentation> result = new LinkedList<>();
        for (ProviderConfigProperty prop : perClientConfigProps) {
            ConfigPropertyRepresentation propRep = getConfigPropertyRep(prop);
            result.add(propRep);
        }

        toReturn.put(providerId, result);
    }

    return toReturn;
}
 
Example #27
Source File: ServerInfoAdminResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setBuiltinProtocolMappers(ServerInfoRepresentation info) {
    info.setBuiltinProtocolMappers(new HashMap<String, List<ProtocolMapperRepresentation>>());
    for (ProviderFactory p : session.getKeycloakSessionFactory().getProviderFactories(LoginProtocol.class)) {
        LoginProtocolFactory factory = (LoginProtocolFactory)p;
        List<ProtocolMapperRepresentation> mappers = new LinkedList<>();
        for (ProtocolMapperModel mapper : factory.getBuiltinMappers().values()) {
            mappers.add(ModelToRepresentation.toRepresentation(mapper));
        }
        info.getBuiltinProtocolMappers().put(p.getId(), mappers);
    }
}
 
Example #28
Source File: ClientRegistrationSpi.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Class<? extends ProviderFactory> getProviderFactoryClass() {
    return ClientRegistrationProviderFactory.class;
}
 
Example #29
Source File: IdentityProviderSpi.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Class<? extends ProviderFactory> getProviderFactoryClass() {
    return IdentityProviderFactory.class;
}
 
Example #30
Source File: HashSpi.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Class<? extends ProviderFactory> getProviderFactoryClass() {
    return HashProviderFactory.class;
}