org.keycloak.Config Java Examples

The following examples show how to use org.keycloak.Config. 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: FilesPlainTextVaultProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void init(Config.Scope config) {
    super.init(config);

    vaultDirectory = config.get("dir");
    if (vaultDirectory == null) {
        logger.debug("PlainTextVaultProviderFactory not configured");
        return;
    }

    vaultPath = Paths.get(vaultDirectory);
    if (!Files.exists(vaultPath)) {
        throw new VaultNotFoundException("The " + vaultPath.toAbsolutePath().toString() + " directory doesn't exist");
    }
    logger.debugf("Configured PlainTextVaultProviderFactory with directory %s", vaultPath.toString());
}
 
Example #2
Source File: JpaUpdate1_2_0_Beta1.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private String getAdminRoleId() throws SQLException, DatabaseException {
    PreparedStatement statement = jdbcConnection.prepareStatement("select ID from " + getTableName("KEYCLOAK_ROLE") + " where NAME = ? AND REALM = ?");
    statement.setString(1, AdminRoles.ADMIN);
    statement.setString(2, Config.getAdminRealm());

    try {
        ResultSet resultSet = statement.executeQuery();
        try {
            if (resultSet.next()) {
                return resultSet.getString("ID");
            } else {
                throw new IllegalStateException("Couldn't find ID of 'admin' role in 'master' realm");
            }
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example #3
Source File: QuarkusCacheManagerProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private InputStream loadConfiguration(Config.Scope config) throws FileNotFoundException {
    String homeDir = System.getProperty("keycloak.home.dir");
    
    if (homeDir == null) {
        log.warn("Keycloak home directory not set.");
        return loadDefaultConfiguration(config);
    }

    Path configPath = Paths.get(homeDir + "/conf/" + getConfigFileName(config));
    
    if (configPath.toFile().exists()) {
        log.debugf("Loading cluster configuration from %s", configPath);
        return FileLookupFactory.newInstance()
                .lookupFileStrict(configPath.toUri(), Thread.currentThread().getContextClassLoader());
    }

    log.infof("Clustering configuration file not found at %s.", configPath);

    return loadDefaultConfiguration(config);
}
 
Example #4
Source File: DMRConfigProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<Config.ConfigProvider> create() {

    ServletContext context = Resteasy.getContextData(ServletContext.class);

    JsonNode node = null;

    try {
        String dmrConfig = loadDmrConfig(context);
        if (dmrConfig != null) {
            node = JsonSerialization.mapper.readTree(dmrConfig);
            ServicesLogger.LOGGER.loadingFrom("standalone.xml or domain.xml");
        }
    } catch (IOException e) {
        LOG.warn("Failed to load DMR config", e);
    }

    return createJsonProvider(node);

}
 
Example #5
Source File: ClientRegistrationAuth.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean hasRoleInModel(String[] roles) {
    ClientModel roleNamespace;
    UserModel user = session.users().getUserById(jwt.getSubject(), realm);
    if (user == null) {
        return false;
    }
    if (realm.getName().equals(Config.getAdminRealm())) {
        roleNamespace = realm.getMasterAdminClient();
    } else {
        roleNamespace = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
    }
    for (String role : roles) {
        RoleModel roleModel = roleNamespace.getRole(role);
        if (user.hasRole(roleModel)) return true;
    }
    return false;
}
 
Example #6
Source File: RealmManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void setupRealmAdminManagement(RealmModel realm) {
    if (realm.getName().equals(Config.getAdminRealm())) { return; } // don't need to do this for master realm

    String realmAdminClientId = getRealmAdminClientId(realm);
    ClientModel realmAdminClient = realm.getClientByClientId(realmAdminClientId);
    if (realmAdminClient == null) {
        realmAdminClient = KeycloakModelUtils.createClient(realm, realmAdminClientId);
        realmAdminClient.setName("${client_" + realmAdminClientId + "}");
    }
    RoleModel adminRole = realmAdminClient.addRole(AdminRoles.REALM_ADMIN);
    adminRole.setDescription("${role_" + AdminRoles.REALM_ADMIN + "}");
    realmAdminClient.setBearerOnly(true);
    realmAdminClient.setFullScopeAllowed(false);
    realmAdminClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

    for (String r : AdminRoles.ALL_REALM_ROLES) {
        addAndSetAdminRole(r, realmAdminClient, adminRole);
    }
    addQueryCompositeRoles(realmAdminClient);
}
 
Example #7
Source File: KeycloakErrorHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private RealmModel resolveRealm() {
    String path = session.getContext().getUri().getPath();
    Matcher m = realmNamePattern.matcher(path);
    String realmName;
    if(m.matches()) {
        realmName = m.group(1);
    } else {
        realmName = Config.getAdminRealm();
    }

    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        realm = realmManager.getRealmByName(Config.getAdminRealm());
    }

    session.getContext().setRealm(realm);

    return realm;
}
 
Example #8
Source File: ImportUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Fully import realm from representation, save it to model and return model of newly created realm
 *
 * @param session
 * @param rep
 * @param strategy specifies whether to overwrite or ignore existing realm or user entries
 * @param skipUserDependent If true, then import of any models, which needs users already imported in DB, will be skipped. For example authorization
 * @return newly imported realm (or existing realm if ignoreExisting is true and realm of this name already exists)
 */
public static boolean importRealm(KeycloakSession session, RealmRepresentation rep, Strategy strategy, boolean skipUserDependent) {
    String realmName = rep.getRealm();
    RealmProvider model = session.realms();
    RealmModel realm = model.getRealmByName(realmName);

    if (realm != null) {
        if (strategy == Strategy.IGNORE_EXISTING) {
            logger.infof("Realm '%s' already exists. Import skipped", realmName);
            return false;
        } else {
            logger.infof("Realm '%s' already exists. Removing it before import", realmName);
            if (Config.getAdminRealm().equals(realm.getId())) {
                // Delete all masterAdmin apps due to foreign key constraints
                for (RealmModel currRealm : model.getRealms()) {
                    currRealm.setMasterAdminClient(null);
                }
            }
            // TODO: For migration between versions, it should be possible to delete just realm but keep it's users
            model.removeRealm(realm.getId());
        }
    }

    RealmManager realmManager = new RealmManager(session);
    realmManager.importRealm(rep, skipUserDependent);

    if (System.getProperty(ExportImportConfig.ACTION) != null) {
        logger.infof("Realm '%s' imported", realmName);
    }
    
    return true;
}
 
Example #9
Source File: QuarkusCacheManagerProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public <C> C getCacheManager(Config.Scope config) {
    try {
        InputStream configurationStream = loadConfiguration(config);
        ConfigurationBuilderHolder builder = new ParserRegistry().parse(configurationStream);

        if (builder.getNamedConfigurationBuilders().get("sessions").clustering().cacheMode().isClustered()) {
            configureTransportStack(config, builder);
        }

        return (C) new DefaultCacheManager(builder, false);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: ModuleThemeProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Config.Scope config) {
    String[] modules = config.getArray("modules");
    if (modules != null) {
        try {
            for (String moduleSpec : modules) {
                Module module = Module.getContextModuleLoader().loadModule(ModuleIdentifier.fromString(moduleSpec));
                ModuleClassLoader classLoader = module.getClassLoader();
                loadThemes(classLoader, classLoader.getResourceAsStream(KEYCLOAK_THEMES_JSON));
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to load themes", e);
        }
    }
}
 
Example #11
Source File: WildflyCacheManagerProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public <C> C getCacheManager(Config.Scope config) {
    String cacheContainer = config.get("cacheContainer");
    
    if (cacheContainer == null) {
        return null;
    }
    
    try {
        return (C) new InitialContext().lookup(cacheContainer);
    } catch (Exception e) {
        throw new RuntimeException("Failed to retrieve cache container", e);
    }
}
 
Example #12
Source File: RealmManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean postponeMasterClientSetup(RealmRepresentation rep) {
    if (!Config.getAdminRealm().equals(rep.getRealm())) {
        return false;
    }

    return hasRealmAdminManagementClient(rep);
}
 
Example #13
Source File: MgmtPermissions.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public ClientModel getRealmManagementClient() {
    ClientModel client = null;
    if (realm.getName().equals(Config.getAdminRealm())) {
        client = realm.getClientByClientId(Config.getAdminRealm() + "-realm");
    } else {
        client = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);

    }
    return client;
}
 
Example #14
Source File: GlobalRequestResponseFilterResourceProvider.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Config.Scope config) {
    ResteasyProviderFactory.getInstance().getContainerRequestFilterRegistry()
            .registerSingleton(GlobalRequestResponseFilter.INSTANCE);

    ResteasyProviderFactory.getInstance().getContainerResponseFilterRegistry()
            .registerSingleton(GlobalRequestResponseFilter.INSTANCE);
}
 
Example #15
Source File: ApplianceBootstrap.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean createMasterRealm() {
    if (!isNewInstall()) {
        throw new IllegalStateException("Can't create default realm as realms already exists");
    }

    String adminRealmName = Config.getAdminRealm();
    ServicesLogger.LOGGER.initializingAdminRealm(adminRealmName);

    RealmManager manager = new RealmManager(session);
    RealmModel realm = manager.createRealm(adminRealmName, adminRealmName);
    realm.setName(adminRealmName);
    realm.setDisplayName(Version.NAME);
    realm.setDisplayNameHtml(Version.NAME_HTML);
    realm.setEnabled(true);
    realm.addRequiredCredential(CredentialRepresentation.PASSWORD);
    realm.setSsoSessionIdleTimeout(1800);
    realm.setAccessTokenLifespan(60);
    realm.setAccessTokenLifespanForImplicitFlow(Constants.DEFAULT_ACCESS_TOKEN_LIFESPAN_FOR_IMPLICIT_FLOW_TIMEOUT);
    realm.setSsoSessionMaxLifespan(36000);
    realm.setOfflineSessionIdleTimeout(Constants.DEFAULT_OFFLINE_SESSION_IDLE_TIMEOUT);
    // KEYCLOAK-7688 Offline Session Max for Offline Token
    realm.setOfflineSessionMaxLifespanEnabled(false);
    realm.setOfflineSessionMaxLifespan(Constants.DEFAULT_OFFLINE_SESSION_MAX_LIFESPAN);
    realm.setAccessCodeLifespan(60);
    realm.setAccessCodeLifespanUserAction(300);
    realm.setAccessCodeLifespanLogin(1800);
    realm.setSslRequired(SslRequired.EXTERNAL);
    realm.setRegistrationAllowed(false);
    realm.setRegistrationEmailAsUsername(false);

    session.getContext().setRealm(realm);

    return true;
}
 
Example #16
Source File: QuarkusLifecycleObserver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void createAdminUser() {
    String adminUserName = System.getenv(KEYCLOAK_ADMIN_ENV_VAR);
    String adminPassword = System.getenv(KEYCLOAK_ADMIN_PASSWORD_ENV_VAR);

    if ((adminUserName == null || adminUserName.trim().length() == 0)
            || (adminPassword == null || adminPassword.trim().length() == 0)) {
        return;
    }

    KeycloakSessionFactory sessionFactory = application.getSessionFactory();
    KeycloakSession session = sessionFactory.create();
    KeycloakTransactionManager transaction = session.getTransactionManager();

    try {
        transaction.begin();

        new ApplianceBootstrap(session).createMasterRealmUser(adminUserName, adminPassword);
        ServicesLogger.LOGGER.addUserSuccess(adminUserName, Config.getAdminRealm());

        transaction.commit();
    } catch (IllegalStateException e) {
        session.getTransactionManager().rollback();
        ServicesLogger.LOGGER.addUserFailedUserExists(adminUserName, Config.getAdminRealm());
    } catch (Throwable t) {
        session.getTransactionManager().rollback();
        ServicesLogger.LOGGER.addUserFailed(t, adminUserName, Config.getAdminRealm());
    } finally {
        session.close();
    }
}
 
Example #17
Source File: AbstractClientRegistrationPolicyFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Config.Scope config) {
}
 
Example #18
Source File: RealmManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public RealmModel getKeycloakAdminstrationRealm() {
    return getRealm(Config.getAdminRealm());
}
 
Example #19
Source File: SecurityHeadersProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
default void init(Config.Scope config) {
}
 
Example #20
Source File: UpdateUserLocaleAction.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Config.Scope config) {
}
 
Example #21
Source File: AbstractOIDCProtocolMapper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Config.Scope config) {
}
 
Example #22
Source File: InfinispanUserSessionProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Config.Scope config) {
    this.config = config;
}
 
Example #23
Source File: RegexPatternsPasswordPolicyProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Config.Scope config) {
}
 
Example #24
Source File: KeycloakMetricsEventListenerFactory.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Config.Scope config) {

    MetricRegistry metricsRegistry = lookupMetricsRegistry();
    this.keycloakMetrics = new KeycloakMetrics(metricsRegistry);
}
 
Example #25
Source File: JpaEventStoreProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Config.Scope config) {
    maxDetailLength = config.getInt("max-detail-length", 0);
}
 
Example #26
Source File: OIDCClientDescriptionConverterFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Config.Scope config) {
}
 
Example #27
Source File: MigrateTo1_9_0.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void migrate(KeycloakSession session) {
    RealmModel realm = session.realms().getRealm(Config.getAdminRealm());
    if (realm != null && realm.getDisplayNameHtml() != null && realm.getDisplayNameHtml().equals("<strong>Keycloak</strong>")) {
        realm.setDisplayNameHtml("<div class=\"kc-logo-text\"><span>Keycloak</span></div>");
    }
}
 
Example #28
Source File: EmbeddedKeycloakApplication.java    From spring-security-oauth with MIT License 4 votes vote down vote up
protected void loadConfig() {
    JsonConfigProviderFactory factory = new RegularJsonConfigProviderFactory();
    Config.init(factory.create()
        .orElseThrow(() -> new NoSuchElementException("No value present")));
}
 
Example #29
Source File: EmbeddedKeycloakApplication.java    From spring-security-oauth with MIT License 4 votes vote down vote up
protected void loadConfig() {
    JsonConfigProviderFactory factory = new RegularJsonConfigProviderFactory();
    Config.init(factory.create()
        .orElseThrow(() -> new NoSuchElementException("No value present")));
}
 
Example #30
Source File: InfinispanHealthIndicator.java    From keycloak-health-checks with Apache License 2.0 4 votes vote down vote up
InfinispanHealthIndicator(Config.Scope config) {
    super("infinispan");
}