Java Code Examples for org.keycloak.representations.idm.RealmRepresentation#getClients()

The following examples show how to use org.keycloak.representations.idm.RealmRepresentation#getClients() . 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: KeycloakModelUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static ClientRepresentation createClient(RealmRepresentation realm, String name) {
    ClientRepresentation app = new ClientRepresentation();
    app.setName(name);
    app.setClientId(name);
    List<ClientRepresentation> clients = realm.getClients();
    if (clients != null) {
        clients.add(app);
    } else {
        realm.setClients(Arrays.asList(app));
    }
    app.setClientAuthenticatorType(getDefaultClientAuthenticatorType());
    generateSecret(app);
    app.setFullScopeAllowed(true);

    return app;
}
 
Example 2
Source File: AbstractAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Modifies baseUrl, adminUrl and redirectUris for client based on real
 * deployment url of the app.
 *
 * @param realm
 * @param clientId
 * @param deploymentUrl
 */
protected void fixClientUrisUsingDeploymentUrl(RealmRepresentation realm, String clientId, String deploymentUrl) {
    for (ClientRepresentation client : realm.getClients()) {
        if (clientId.equals(client.getClientId())) {
            if (client.getBaseUrl() != null) {
                client.setBaseUrl(deploymentUrl);
            }
            if (client.getAdminUrl() != null) {
                client.setAdminUrl(deploymentUrl);
            }
            List<String> redirectUris = client.getRedirectUris();
            if (redirectUris != null) {
                List<String> newRedirectUris = new ArrayList<>();
                for (String uri : redirectUris) {
                    newRedirectUris.add(deploymentUrl + "/*");
                }
                client.setRedirectUris(newRedirectUris);
            }
        }
    }
}
 
Example 3
Source File: AbstractAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void modifyClientRedirectUris(RealmRepresentation realm, String regex, String... replacement) {
    if (realm.getClients() != null) {
        for (ClientRepresentation client : realm.getClients()) {
            List<String> redirectUris = client.getRedirectUris();
            if (redirectUris != null) {
                List<String> newRedirectUris = new ArrayList<>();
                for (String uri : redirectUris) {
                    for (String uriReplacement : replacement) {
                        newRedirectUris.add(uri.replaceAll(regex, uriReplacement));
                    }

                }
                client.setRedirectUris(newRedirectUris);
            }
        }
    }
}
 
Example 4
Source File: AbstractAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void modifyClientWebOrigins(RealmRepresentation realm, String regex, String... replacement) {
    if (realm.getClients() != null) {
        for (ClientRepresentation client : realm.getClients()) {
            List<String> webOrigins = client.getWebOrigins();
            if (webOrigins != null) {
                List<String> newWebOrigins = new ArrayList<>();
                for (String uri : webOrigins) {
                    for (String originReplacement : replacement) {
                        newWebOrigins.add(uri.replaceAll(regex, originReplacement));
                    }
                }
                client.setWebOrigins(newWebOrigins);
            }
        }
    }
}
 
Example 5
Source File: AbstractAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void modifySAMLClientsAttributes(RealmRepresentation realm, String regex, String replacement) {
    if (realm.getClients() != null) {
        for (ClientRepresentation client : realm.getClients()) {
            if (client.getProtocol() != null && client.getProtocol().equals("saml")) {
                log.debug("Modifying attributes of SAML client: " + client.getClientId());
                for (Map.Entry<String, String> entry : client.getAttributes().entrySet()) {
                    client.getAttributes().put(entry.getKey(), entry.getValue().replaceAll(regex, replacement));
                }
            }
        }
    }
}
 
Example 6
Source File: RealmManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void setupClientServiceAccountsAndAuthorizationOnImport(RealmRepresentation rep, boolean skipUserDependent) {
    List<ClientRepresentation> clients = rep.getClients();
    // do not initialize services accounts or authorization if skipUserDependent
    // they need the users and should be done at the end in dir import
    if (clients != null && !skipUserDependent) {
        ClientManager clientManager = new ClientManager(this);

        for (ClientRepresentation client : clients) {
            ClientModel clientModel = this.getRealmByName(rep.getRealm()).getClientById(client.getId());

            UserModel serviceAccount = null;
            if (clientModel.isServiceAccountsEnabled()) {
                serviceAccount = this.getSession().users().getServiceAccount(clientModel);
                if (serviceAccount == null) {
                    // initialize the service account if the account is missing
                    clientManager.enableServiceAccount(clientModel);
                }
            }

            if (Boolean.TRUE.equals(client.getAuthorizationServicesEnabled())) {
                // just create the default roles if the service account was missing in the import
                RepresentationToModel.createResourceServer(clientModel, session, serviceAccount == null);
                RepresentationToModel.importAuthorizationSettings(client, clientModel, session);
            }
        }
    }
}
 
Example 7
Source File: AbstractTestRealmKeycloakTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected ClientRepresentation findTestApp(RealmRepresentation testRealm) {
    for (ClientRepresentation client : testRealm.getClients()) {
        if (client.getClientId().equals("test-app")) return client;
    }

    return null;
}
 
Example 8
Source File: RealmRepUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ClientRepresentation findClientByClientId(RealmRepresentation testRealm, String clientId) {
    for (ClientRepresentation client : testRealm.getClients()) {
        if (client.getClientId().equals(clientId)) return client;
    }

    return null;
}
 
Example 9
Source File: AbstractAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void modifySamlMasterURLs(RealmRepresentation realm, String regex, String replacement) {
    if (realm.getClients() != null) {
        for (ClientRepresentation client : realm.getClients()) {
            if (client.getProtocol() != null && client.getProtocol().equals("saml")) {
                log.debug("Modifying master URL of SAML client: " + client.getClientId());
                String masterUrl = client.getAdminUrl();
                if (masterUrl == null) {
                    masterUrl = client.getBaseUrl();
                }
                masterUrl = masterUrl.replaceFirst(regex, replacement);
                client.setAdminUrl(masterUrl + ((!masterUrl.endsWith("/saml")) ? "/saml" : ""));
            }
        }
    }
}
 
Example 10
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static Map<String, ClientModel> createClients(KeycloakSession session, RealmRepresentation rep, RealmModel realm, Map<String, String> mappedFlows) {
    Map<String, ClientModel> appMap = new HashMap<String, ClientModel>();
    for (ClientRepresentation resourceRep : rep.getClients()) {
        ClientModel app = createClient(session, realm, resourceRep, false, mappedFlows);
        appMap.put(app.getClientId(), app);

        ClientValidationUtil.validate(session, app, false, c -> {
            throw new RuntimeException("Invalid client " + app.getClientId() + ": " + c.getError());
        });
    }
    return appMap;
}
 
Example 11
Source File: AbstractAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void modifyClientUrls(RealmRepresentation realm, String regex, String replacement) {
    if (realm.getClients() != null) {
        for (ClientRepresentation client : realm.getClients()) {
            String baseUrl = client.getBaseUrl();
            if (baseUrl != null) {
                client.setBaseUrl(baseUrl.replaceAll(regex, replacement));
            }
            String adminUrl = client.getAdminUrl();
            if (adminUrl != null) {
                client.setAdminUrl(adminUrl.replaceAll(regex, replacement));
            }
        }
    }
}
 
Example 12
Source File: AbstractAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void modifyClientJWKSUrl(RealmRepresentation realm, String regex, String replacement) {
    if (realm.getClients() != null) {
        realm.getClients().stream().
                filter(client -> "client-jwt".equals(client.getClientAuthenticatorType()) && client.getAttributes().containsKey("jwks.url")).
                forEach(client -> {
            Map<String, String> attr = client.getAttributes();
            attr.put("jwks.url", attr.get("jwks.url").replaceFirst(regex, replacement));
            client.setAttributes(attr);
        });
    }
}
 
Example 13
Source File: GroupMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ClientRepresentation getClientByAlias(RealmRepresentation testRealmRep, String alias) {
    for (ClientRepresentation client: testRealmRep.getClients()) {
        if (alias.equals(client.getClientId())) {
            return client;
        }
    }
    return null;
}
 
Example 14
Source File: GroupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation testRealmRep = loadTestRealm(testRealms);

    testRealmRep.setEventsEnabled(true);

    List<UserRepresentation> users = testRealmRep.getUsers();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("direct-login");
    user.setEmail("direct-login@localhost");
    user.setEnabled(true);
    List<CredentialRepresentation> credentials = new LinkedList<>();
    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue("password");
    credentials.add(credential);
    user.setCredentials(credentials);
    users.add(user);

    List<ClientRepresentation> clients = testRealmRep.getClients();

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("resource-owner");
    client.setDirectAccessGrantsEnabled(true);
    client.setSecret("secret");
    clients.add(client);
}
 
Example 15
Source File: HoKTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addRedirectUrlForTls(RealmRepresentation testRealm, String clientId) {
    for (ClientRepresentation client : testRealm.getClients()) {
        if (client.getClientId().equals(clientId)) {
            URI baseUri = URI.create(client.getRedirectUris().get(0));
            URI redir = URI.create("https://localhost:" + System.getProperty("auth.server.https.port", "8543") + baseUri.getRawPath());
            client.getRedirectUris().add(redir.toString());
            break;
        }
    }
}
 
Example 16
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void importRealmAuthorizationSettings(RealmRepresentation rep, RealmModel newRealm, KeycloakSession session) {
    if (rep.getClients() != null) {
        rep.getClients().forEach(clientRepresentation -> {
            ClientModel client = newRealm.getClientByClientId(clientRepresentation.getClientId());
            importAuthorizationSettings(clientRepresentation, client, session);
        });
    }
}
 
Example 17
Source File: RealmRepUtil.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static ClientRepresentation findClientById(RealmRepresentation testRealm, String id) {
    for (ClientRepresentation client : testRealm.getClients()) {
        if (client.getId().equals(id)) return client;
    }
    return null;
}
 
Example 18
Source File: RealmManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * if "skipUserDependent" is true, then import of any models, which needs users already imported in DB, will be skipped. For example authorization
 */
public RealmModel importRealm(RealmRepresentation rep, boolean skipUserDependent) {
    String id = rep.getId();
    if (id == null) {
        id = KeycloakModelUtils.generateId();
    }
    RealmModel realm = model.createRealm(id, rep.getRealm());
    ReservedCharValidator.validate(rep.getRealm());
    realm.setName(rep.getRealm());

    // setup defaults

    setupRealmDefaults(realm);

    boolean postponeMasterClientSetup = postponeMasterClientSetup(rep);
    if (!postponeMasterClientSetup) {
        setupMasterAdminManagement(realm);
    }

    if (!hasRealmAdminManagementClient(rep)) setupRealmAdminManagement(realm);
    if (!hasAccountManagementClient(rep)) setupAccountManagement(realm);

    boolean postponeImpersonationSetup = false;
    if (hasRealmAdminManagementClient(rep)) {
        postponeImpersonationSetup = true;
    } else {
        setupImpersonationService(realm);
    }


    if (!hasBrokerClient(rep)) setupBrokerService(realm);
    if (!hasAdminConsoleClient(rep)) setupAdminConsole(realm);

    boolean postponeAdminCliSetup = false;
    if (!hasAdminCliClient(rep)) {
        if (hasRealmAdminManagementClient(rep)) {
            postponeAdminCliSetup = true;
        } else {
            setupAdminCli(realm);
        }
    }

    if (!hasRealmRole(rep, Constants.OFFLINE_ACCESS_ROLE) || !hasClientScope(rep, Constants.OFFLINE_ACCESS_ROLE)) {
        setupOfflineTokens(realm, rep);
    }

    if (rep.getClientScopes() == null) {
        createDefaultClientScopes(realm);
    }

    RepresentationToModel.importRealm(session, rep, realm, skipUserDependent);
    List<ClientRepresentation> clients = rep.getClients();

    setupClientServiceAccountsAndAuthorizationOnImport(rep, skipUserDependent);

    setupAdminConsoleLocaleMapper(realm);

    if (postponeMasterClientSetup) {
        setupMasterAdminManagement(realm);
    }

    if (rep.getRoles() != null || hasRealmAdminManagementClient(rep)) {
    	// Assert all admin roles are available once import took place. This is needed due to import from previous version where JSON file may not contain all admin roles
    	checkMasterAdminManagementRoles(realm);
    	checkRealmAdminManagementRoles(realm);
    }

    // Could happen when migrating from older version and I have exported JSON file, which contains "realm-management" client but not "impersonation" client
    // I need to postpone impersonation because it needs "realm-management" client and its roles set
    if (postponeImpersonationSetup) {
        setupImpersonationService(realm);
        String realmAdminClientId = getRealmAdminClientId(realm);
     }

    if (postponeAdminCliSetup) {
        setupAdminCli(realm);
    }

    setupAuthenticationFlows(realm);
    setupRequiredActions(realm);

    // Refresh periodic sync tasks for configured storageProviders
    List<UserStorageProviderModel> storageProviders = realm.getUserStorageProviders();
    UserStorageSyncManager storageSync = new UserStorageSyncManager();
    for (UserStorageProviderModel provider : storageProviders) {
        storageSync.notifyToRefreshPeriodicSync(session, realm, provider, false);
    }

    setupAuthorizationServices(realm);
    setupClientRegistrations(realm);

    if (rep.getKeycloakVersion() != null) {
        MigrationModelManager.migrateImport(session, realm, rep, skipUserDependent);
    }

    fireRealmPostCreate(realm);

    return realm;
}