Search in sources :

Example 1 with ComponentExportRepresentation

use of org.keycloak.representations.idm.ComponentExportRepresentation in project keycloak by keycloak.

the class ExportUtils method exportComponents.

public static MultivaluedHashMap<String, ComponentExportRepresentation> exportComponents(RealmModel realm, String parentId) {
    MultivaluedHashMap<String, ComponentExportRepresentation> components = new MultivaluedHashMap<>();
    realm.getComponentsStream(parentId).forEach(component -> {
        ComponentExportRepresentation compRep = new ComponentExportRepresentation();
        compRep.setId(component.getId());
        compRep.setProviderId(component.getProviderId());
        compRep.setConfig(component.getConfig());
        compRep.setName(component.getName());
        compRep.setSubType(component.getSubType());
        compRep.setSubComponents(exportComponents(realm, component.getId()));
        components.add(component.getProviderType(), compRep);
    });
    return components;
}
Also used : MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation)

Example 2 with ComponentExportRepresentation

use of org.keycloak.representations.idm.ComponentExportRepresentation in project keycloak by keycloak.

the class ExportUtils method exportRealm.

public static RealmRepresentation exportRealm(KeycloakSession session, RealmModel realm, ExportOptions options, boolean internal) {
    RealmRepresentation rep = ModelToRepresentation.toRepresentation(session, realm, internal);
    ModelToRepresentation.exportAuthenticationFlows(realm, rep);
    ModelToRepresentation.exportRequiredActions(realm, rep);
    // Project/product version
    rep.setKeycloakVersion(Version.VERSION_KEYCLOAK);
    // Client Scopes
    rep.setClientScopes(realm.getClientScopesStream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList()));
    rep.setDefaultDefaultClientScopes(realm.getDefaultClientScopesStream(true).map(ClientScopeModel::getName).collect(Collectors.toList()));
    rep.setDefaultOptionalClientScopes(realm.getDefaultClientScopesStream(false).map(ClientScopeModel::getName).collect(Collectors.toList()));
    // Clients
    List<ClientModel> clients = new LinkedList<>();
    if (options.isClientsIncluded()) {
        // we iterate over all clients in the stream.
        // only those client models that can be translated into a valid client representation will be added to the client list
        // that is later used to retrieve related information about groups and roles
        List<ClientRepresentation> clientReps = ModelToRepresentation.filterValidRepresentations(realm.getClientsStream(), app -> {
            ClientRepresentation clientRepresentation = exportClient(session, app);
            clients.add(app);
            return clientRepresentation;
        }).collect(Collectors.toList());
        rep.setClients(clientReps);
    }
    // Groups and Roles
    if (options.isGroupsAndRolesIncluded()) {
        ModelToRepresentation.exportGroups(realm, rep);
        Map<String, List<RoleRepresentation>> clientRolesReps = new HashMap<>();
        List<RoleRepresentation> realmRoleReps = exportRoles(realm.getRolesStream());
        RolesRepresentation rolesRep = new RolesRepresentation();
        if (!realmRoleReps.isEmpty()) {
            rolesRep.setRealm(realmRoleReps);
        }
        if (options.isClientsIncluded()) {
            for (ClientModel client : clients) {
                Stream<RoleModel> currentAppRoles = client.getRolesStream();
                List<RoleRepresentation> currentAppRoleReps = exportRoles(currentAppRoles);
                clientRolesReps.put(client.getClientId(), currentAppRoleReps);
            }
            if (clientRolesReps.size() > 0) {
                rolesRep.setClient(clientRolesReps);
            }
        }
        rep.setRoles(rolesRep);
    }
    // Scopes
    Map<String, List<ScopeMappingRepresentation>> clientScopeReps = new HashMap<>();
    if (options.isClientsIncluded()) {
        List<ClientModel> allClients = new ArrayList<>(clients);
        // Scopes of clients
        for (ClientModel client : allClients) {
            Set<RoleModel> clientScopes = client.getScopeMappingsStream().collect(Collectors.toSet());
            ScopeMappingRepresentation scopeMappingRep = null;
            for (RoleModel scope : clientScopes) {
                if (scope.getContainer() instanceof RealmModel) {
                    if (scopeMappingRep == null) {
                        scopeMappingRep = rep.clientScopeMapping(client.getClientId());
                    }
                    scopeMappingRep.role(scope.getName());
                } else {
                    ClientModel app = (ClientModel) scope.getContainer();
                    String appName = app.getClientId();
                    List<ScopeMappingRepresentation> currentAppScopes = clientScopeReps.get(appName);
                    if (currentAppScopes == null) {
                        currentAppScopes = new ArrayList<>();
                        clientScopeReps.put(appName, currentAppScopes);
                    }
                    ScopeMappingRepresentation currentClientScope = null;
                    for (ScopeMappingRepresentation scopeMapping : currentAppScopes) {
                        if (client.getClientId().equals(scopeMapping.getClient())) {
                            currentClientScope = scopeMapping;
                            break;
                        }
                    }
                    if (currentClientScope == null) {
                        currentClientScope = new ScopeMappingRepresentation();
                        currentClientScope.setClient(client.getClientId());
                        currentAppScopes.add(currentClientScope);
                    }
                    currentClientScope.role(scope.getName());
                }
            }
        }
    }
    // Scopes of client scopes
    realm.getClientScopesStream().forEach(clientScope -> {
        Set<RoleModel> clientScopes = clientScope.getScopeMappingsStream().collect(Collectors.toSet());
        ScopeMappingRepresentation scopeMappingRep = null;
        for (RoleModel scope : clientScopes) {
            if (scope.getContainer() instanceof RealmModel) {
                if (scopeMappingRep == null) {
                    scopeMappingRep = rep.clientScopeScopeMapping(clientScope.getName());
                }
                scopeMappingRep.role(scope.getName());
            } else {
                ClientModel app = (ClientModel) scope.getContainer();
                String appName = app.getClientId();
                List<ScopeMappingRepresentation> currentAppScopes = clientScopeReps.get(appName);
                if (currentAppScopes == null) {
                    currentAppScopes = new ArrayList<>();
                    clientScopeReps.put(appName, currentAppScopes);
                }
                ScopeMappingRepresentation currentClientTemplateScope = null;
                for (ScopeMappingRepresentation scopeMapping : currentAppScopes) {
                    if (clientScope.getName().equals(scopeMapping.getClientScope())) {
                        currentClientTemplateScope = scopeMapping;
                        break;
                    }
                }
                if (currentClientTemplateScope == null) {
                    currentClientTemplateScope = new ScopeMappingRepresentation();
                    currentClientTemplateScope.setClientScope(clientScope.getName());
                    currentAppScopes.add(currentClientTemplateScope);
                }
                currentClientTemplateScope.role(scope.getName());
            }
        }
    });
    if (clientScopeReps.size() > 0) {
        rep.setClientScopeMappings(clientScopeReps);
    }
    // Finally users if needed
    if (options.isUsersIncluded()) {
        List<UserRepresentation> users = session.users().getUsersStream(realm, true).map(user -> exportUser(session, realm, user, options, internal)).collect(Collectors.toList());
        if (users.size() > 0) {
            rep.setUsers(users);
        }
        List<UserRepresentation> federatedUsers = session.userFederatedStorage().getStoredUsersStream(realm, 0, -1).map(user -> exportFederatedUser(session, realm, user, options)).collect(Collectors.toList());
        if (federatedUsers.size() > 0) {
            rep.setFederatedUsers(federatedUsers);
        }
    } else if (options.isClientsIncluded() && options.isOnlyServiceAccountsIncluded()) {
        List<UserRepresentation> users = new LinkedList<>();
        for (ClientModel app : clients) {
            if (app.isServiceAccountsEnabled() && !app.isPublicClient() && !app.isBearerOnly()) {
                UserModel user = session.users().getServiceAccount(app);
                if (user != null) {
                    UserRepresentation userRep = exportUser(session, realm, user, options, internal);
                    users.add(userRep);
                }
            }
        }
        if (users.size() > 0) {
            rep.setUsers(users);
        }
    }
    // components
    MultivaluedHashMap<String, ComponentExportRepresentation> components = exportComponents(realm, realm.getId());
    rep.setComponents(components);
    return rep;
}
Also used : ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Version(org.keycloak.common.Version) RoleContainerModel(org.keycloak.models.RoleContainerModel) Map(java.util.Map) ModelToRepresentation.toRepresentation(org.keycloak.models.utils.ModelToRepresentation.toRepresentation) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) UserConsentRepresentation(org.keycloak.representations.idm.UserConsentRepresentation) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Collection(java.util.Collection) AuthorizationProviderFactory(org.keycloak.authorization.AuthorizationProviderFactory) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) PolicyStore(org.keycloak.authorization.store.PolicyStore) Collectors(java.util.stream.Collectors) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) List(java.util.List) Stream(java.util.stream.Stream) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) Profile(org.keycloak.common.Profile) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ScopeMappingRepresentation(org.keycloak.representations.idm.ScopeMappingRepresentation) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UserModel(org.keycloak.models.UserModel) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) JsonEncoding(com.fasterxml.jackson.core.JsonEncoding) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) LinkedList(java.util.LinkedList) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ResourceServer(org.keycloak.authorization.model.ResourceServer) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) OutputStream(java.io.OutputStream) RolesRepresentation(org.keycloak.representations.idm.RolesRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) CredentialModel(org.keycloak.credential.CredentialModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) JsonSerialization(org.keycloak.util.JsonSerialization) Policy(org.keycloak.authorization.model.Policy) JsonFactory(com.fasterxml.jackson.core.JsonFactory) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) Resource(org.keycloak.authorization.model.Resource) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) HashMap(java.util.HashMap) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) ScopeMappingRepresentation(org.keycloak.representations.idm.ScopeMappingRepresentation) ArrayList(java.util.ArrayList) ClientScopeModel(org.keycloak.models.ClientScopeModel) RoleModel(org.keycloak.models.RoleModel) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) RolesRepresentation(org.keycloak.representations.idm.RolesRepresentation) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) LinkedList(java.util.LinkedList) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientModel(org.keycloak.models.ClientModel)

Example 3 with ComponentExportRepresentation

use of org.keycloak.representations.idm.ComponentExportRepresentation in project keycloak by keycloak.

the class RepresentationToModel method importRealm.

public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm, boolean skipUserDependent) {
    convertDeprecatedSocialProviders(rep);
    convertDeprecatedApplications(session, rep);
    convertDeprecatedClientTemplates(rep);
    newRealm.setName(rep.getRealm());
    if (rep.getDisplayName() != null)
        newRealm.setDisplayName(rep.getDisplayName());
    if (rep.getDisplayNameHtml() != null)
        newRealm.setDisplayNameHtml(rep.getDisplayNameHtml());
    if (rep.isEnabled() != null)
        newRealm.setEnabled(rep.isEnabled());
    if (rep.isUserManagedAccessAllowed() != null)
        newRealm.setUserManagedAccessAllowed(rep.isUserManagedAccessAllowed());
    if (rep.isBruteForceProtected() != null)
        newRealm.setBruteForceProtected(rep.isBruteForceProtected());
    if (rep.isPermanentLockout() != null)
        newRealm.setPermanentLockout(rep.isPermanentLockout());
    if (rep.getMaxFailureWaitSeconds() != null)
        newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
    if (rep.getMinimumQuickLoginWaitSeconds() != null)
        newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
    if (rep.getWaitIncrementSeconds() != null)
        newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
    if (rep.getQuickLoginCheckMilliSeconds() != null)
        newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
    if (rep.getMaxDeltaTimeSeconds() != null)
        newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
    if (rep.getFailureFactor() != null)
        newRealm.setFailureFactor(rep.getFailureFactor());
    if (rep.isEventsEnabled() != null)
        newRealm.setEventsEnabled(rep.isEventsEnabled());
    if (rep.getEnabledEventTypes() != null)
        newRealm.setEnabledEventTypes(new HashSet<>(rep.getEnabledEventTypes()));
    if (rep.getEventsExpiration() != null)
        newRealm.setEventsExpiration(rep.getEventsExpiration());
    if (rep.getEventsListeners() != null)
        newRealm.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
    if (rep.isAdminEventsEnabled() != null)
        newRealm.setAdminEventsEnabled(rep.isAdminEventsEnabled());
    if (rep.isAdminEventsDetailsEnabled() != null)
        newRealm.setAdminEventsDetailsEnabled(rep.isAdminEventsDetailsEnabled());
    if (rep.getNotBefore() != null)
        newRealm.setNotBefore(rep.getNotBefore());
    if (rep.getDefaultSignatureAlgorithm() != null)
        newRealm.setDefaultSignatureAlgorithm(rep.getDefaultSignatureAlgorithm());
    else
        newRealm.setDefaultSignatureAlgorithm(Constants.DEFAULT_SIGNATURE_ALGORITHM);
    if (rep.getRevokeRefreshToken() != null)
        newRealm.setRevokeRefreshToken(rep.getRevokeRefreshToken());
    else
        newRealm.setRevokeRefreshToken(false);
    if (rep.getRefreshTokenMaxReuse() != null)
        newRealm.setRefreshTokenMaxReuse(rep.getRefreshTokenMaxReuse());
    else
        newRealm.setRefreshTokenMaxReuse(0);
    if (rep.getAccessTokenLifespan() != null)
        newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
    else
        newRealm.setAccessTokenLifespan(300);
    if (rep.getAccessTokenLifespanForImplicitFlow() != null)
        newRealm.setAccessTokenLifespanForImplicitFlow(rep.getAccessTokenLifespanForImplicitFlow());
    else
        newRealm.setAccessTokenLifespanForImplicitFlow(Constants.DEFAULT_ACCESS_TOKEN_LIFESPAN_FOR_IMPLICIT_FLOW_TIMEOUT);
    if (rep.getSsoSessionIdleTimeout() != null)
        newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
    else
        newRealm.setSsoSessionIdleTimeout(1800);
    if (rep.getSsoSessionMaxLifespan() != null)
        newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
    else
        newRealm.setSsoSessionMaxLifespan(36000);
    if (rep.getSsoSessionMaxLifespanRememberMe() != null)
        newRealm.setSsoSessionMaxLifespanRememberMe(rep.getSsoSessionMaxLifespanRememberMe());
    if (rep.getSsoSessionIdleTimeoutRememberMe() != null)
        newRealm.setSsoSessionIdleTimeoutRememberMe(rep.getSsoSessionIdleTimeoutRememberMe());
    if (rep.getOfflineSessionIdleTimeout() != null)
        newRealm.setOfflineSessionIdleTimeout(rep.getOfflineSessionIdleTimeout());
    else
        newRealm.setOfflineSessionIdleTimeout(Constants.DEFAULT_OFFLINE_SESSION_IDLE_TIMEOUT);
    // KEYCLOAK-7688 Offline Session Max for Offline Token
    if (rep.getOfflineSessionMaxLifespanEnabled() != null)
        newRealm.setOfflineSessionMaxLifespanEnabled(rep.getOfflineSessionMaxLifespanEnabled());
    else
        newRealm.setOfflineSessionMaxLifespanEnabled(false);
    if (rep.getOfflineSessionMaxLifespan() != null)
        newRealm.setOfflineSessionMaxLifespan(rep.getOfflineSessionMaxLifespan());
    else
        newRealm.setOfflineSessionMaxLifespan(Constants.DEFAULT_OFFLINE_SESSION_MAX_LIFESPAN);
    if (rep.getClientSessionIdleTimeout() != null)
        newRealm.setClientSessionIdleTimeout(rep.getClientSessionIdleTimeout());
    if (rep.getClientSessionMaxLifespan() != null)
        newRealm.setClientSessionMaxLifespan(rep.getClientSessionMaxLifespan());
    if (rep.getClientOfflineSessionIdleTimeout() != null)
        newRealm.setClientOfflineSessionIdleTimeout(rep.getClientOfflineSessionIdleTimeout());
    if (rep.getClientOfflineSessionMaxLifespan() != null)
        newRealm.setClientOfflineSessionMaxLifespan(rep.getClientOfflineSessionMaxLifespan());
    if (rep.getAccessCodeLifespan() != null)
        newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
    else
        newRealm.setAccessCodeLifespan(60);
    if (rep.getAccessCodeLifespanUserAction() != null)
        newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
    else
        newRealm.setAccessCodeLifespanUserAction(300);
    if (rep.getAccessCodeLifespanLogin() != null)
        newRealm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
    else
        newRealm.setAccessCodeLifespanLogin(1800);
    if (rep.getActionTokenGeneratedByAdminLifespan() != null)
        newRealm.setActionTokenGeneratedByAdminLifespan(rep.getActionTokenGeneratedByAdminLifespan());
    else
        newRealm.setActionTokenGeneratedByAdminLifespan(12 * 60 * 60);
    if (rep.getActionTokenGeneratedByUserLifespan() != null)
        newRealm.setActionTokenGeneratedByUserLifespan(rep.getActionTokenGeneratedByUserLifespan());
    else
        newRealm.setActionTokenGeneratedByUserLifespan(newRealm.getAccessCodeLifespanUserAction());
    // OAuth 2.0 Device Authorization Grant
    OAuth2DeviceConfig deviceConfig = newRealm.getOAuth2DeviceConfig();
    deviceConfig.setOAuth2DeviceCodeLifespan(rep.getOAuth2DeviceCodeLifespan());
    deviceConfig.setOAuth2DevicePollingInterval(rep.getOAuth2DevicePollingInterval());
    if (rep.getSslRequired() != null)
        newRealm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
    if (rep.isRegistrationAllowed() != null)
        newRealm.setRegistrationAllowed(rep.isRegistrationAllowed());
    if (rep.isRegistrationEmailAsUsername() != null)
        newRealm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
    if (rep.isRememberMe() != null)
        newRealm.setRememberMe(rep.isRememberMe());
    if (rep.isVerifyEmail() != null)
        newRealm.setVerifyEmail(rep.isVerifyEmail());
    if (rep.isLoginWithEmailAllowed() != null)
        newRealm.setLoginWithEmailAllowed(rep.isLoginWithEmailAllowed());
    if (rep.isDuplicateEmailsAllowed() != null)
        newRealm.setDuplicateEmailsAllowed(rep.isDuplicateEmailsAllowed());
    if (rep.isResetPasswordAllowed() != null)
        newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
    if (rep.isEditUsernameAllowed() != null)
        newRealm.setEditUsernameAllowed(rep.isEditUsernameAllowed());
    if (rep.getLoginTheme() != null)
        newRealm.setLoginTheme(rep.getLoginTheme());
    if (rep.getAccountTheme() != null)
        newRealm.setAccountTheme(rep.getAccountTheme());
    if (rep.getAdminTheme() != null)
        newRealm.setAdminTheme(rep.getAdminTheme());
    if (rep.getEmailTheme() != null)
        newRealm.setEmailTheme(rep.getEmailTheme());
    // todo remove this stuff as its all deprecated
    if (rep.getRequiredCredentials() != null) {
        for (String requiredCred : rep.getRequiredCredentials()) {
            newRealm.addRequiredCredential(requiredCred);
        }
    } else {
        newRealm.addRequiredCredential(CredentialRepresentation.PASSWORD);
    }
    if (rep.getPasswordPolicy() != null)
        newRealm.setPasswordPolicy(PasswordPolicy.parse(session, rep.getPasswordPolicy()));
    if (rep.getOtpPolicyType() != null)
        newRealm.setOTPPolicy(toPolicy(rep));
    else
        newRealm.setOTPPolicy(OTPPolicy.DEFAULT_POLICY);
    WebAuthnPolicy webAuthnPolicy = getWebAuthnPolicyTwoFactor(rep);
    newRealm.setWebAuthnPolicy(webAuthnPolicy);
    webAuthnPolicy = getWebAuthnPolicyPasswordless(rep);
    newRealm.setWebAuthnPolicyPasswordless(webAuthnPolicy);
    updateCibaSettings(rep, newRealm);
    updateParSettings(rep, newRealm);
    Map<String, String> mappedFlows = importAuthenticationFlows(newRealm, rep);
    if (rep.getRequiredActions() != null) {
        for (RequiredActionProviderRepresentation action : rep.getRequiredActions()) {
            RequiredActionProviderModel model = toModel(action);
            MigrationUtils.updateOTPRequiredAction(model);
            newRealm.addRequiredActionProvider(model);
        }
        DefaultRequiredActions.addDeleteAccountAction(newRealm);
    } else {
        DefaultRequiredActions.addActions(newRealm);
    }
    importIdentityProviders(rep, newRealm, session);
    importIdentityProviderMappers(rep, newRealm);
    Map<String, ClientScopeModel> clientScopes = new HashMap<>();
    if (rep.getClientScopes() != null) {
        clientScopes = createClientScopes(session, rep.getClientScopes(), newRealm);
    }
    if (rep.getDefaultDefaultClientScopes() != null) {
        for (String clientScopeName : rep.getDefaultDefaultClientScopes()) {
            ClientScopeModel clientScope = clientScopes.get(clientScopeName);
            if (clientScope != null) {
                newRealm.addDefaultClientScope(clientScope, true);
            } else {
                logger.warnf("Referenced client scope '%s' doesn't exist", clientScopeName);
            }
        }
    }
    if (rep.getDefaultOptionalClientScopes() != null) {
        for (String clientScopeName : rep.getDefaultOptionalClientScopes()) {
            ClientScopeModel clientScope = clientScopes.get(clientScopeName);
            if (clientScope != null) {
                newRealm.addDefaultClientScope(clientScope, false);
            } else {
                logger.warnf("Referenced client scope '%s' doesn't exist", clientScopeName);
            }
        }
    }
    Map<String, ClientModel> createdClients = new HashMap<>();
    if (rep.getClients() != null) {
        createdClients = createClients(session, rep, newRealm, mappedFlows);
    }
    importRoles(rep.getRoles(), newRealm);
    convertDeprecatedDefaultRoles(rep, newRealm);
    if (rep.getClientScopeMappings() != null) {
        for (Map.Entry<String, List<ScopeMappingRepresentation>> entry : rep.getClientScopeMappings().entrySet()) {
            ClientModel app = createdClients.computeIfAbsent(entry.getKey(), k -> newRealm.getClientByClientId(entry.getKey()));
            if (app == null) {
                throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
            }
            createClientScopeMappings(newRealm, app, entry.getValue());
        }
    }
    if (rep.getScopeMappings() != null) {
        Map<String, RoleModel> roleModelMap = newRealm.getRolesStream().collect(Collectors.toMap(RoleModel::getId, Function.identity()));
        for (ScopeMappingRepresentation scope : rep.getScopeMappings()) {
            ScopeContainerModel scopeContainer = getScopeContainerHavingScope(newRealm, scope);
            for (String roleString : scope.getRoles()) {
                final String roleStringTrimmed = roleString.trim();
                RoleModel role = roleModelMap.computeIfAbsent(roleStringTrimmed, k -> newRealm.getRole(roleStringTrimmed));
                if (role == null) {
                    role = newRealm.addRole(roleString);
                    roleModelMap.put(role.getId(), role);
                }
                scopeContainer.addScopeMapping(role);
            }
        }
    }
    if (rep.getSmtpServer() != null) {
        newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer()));
    }
    if (rep.getBrowserSecurityHeaders() != null) {
        newRealm.setBrowserSecurityHeaders(rep.getBrowserSecurityHeaders());
    } else {
        newRealm.setBrowserSecurityHeaders(BrowserSecurityHeaders.realmDefaultHeaders);
    }
    if (rep.getComponents() != null) {
        MultivaluedHashMap<String, ComponentExportRepresentation> components = rep.getComponents();
        String parentId = newRealm.getId();
        importComponents(newRealm, components, parentId);
    }
    importUserFederationProvidersAndMappers(session, rep, newRealm);
    if (rep.getGroups() != null) {
        importGroups(newRealm, rep);
        if (rep.getDefaultGroups() != null) {
            for (String path : rep.getDefaultGroups()) {
                GroupModel found = KeycloakModelUtils.findGroupByPath(newRealm, path);
                if (found == null)
                    throw new RuntimeException("default group in realm rep doesn't exist: " + path);
                newRealm.addDefaultGroup(found);
            }
        }
    }
    if (rep.getUsers() != null) {
        for (UserRepresentation userRep : rep.getUsers()) {
            createUser(session, newRealm, userRep);
        }
    }
    if (rep.getFederatedUsers() != null) {
        for (UserRepresentation userRep : rep.getFederatedUsers()) {
            importFederatedUser(session, newRealm, userRep);
        }
    }
    if (!skipUserDependent) {
        importRealmAuthorizationSettings(rep, newRealm, session);
    }
    if (rep.isInternationalizationEnabled() != null) {
        newRealm.setInternationalizationEnabled(rep.isInternationalizationEnabled());
    }
    if (rep.getSupportedLocales() != null) {
        newRealm.setSupportedLocales(new HashSet<String>(rep.getSupportedLocales()));
    }
    if (rep.getDefaultLocale() != null) {
        newRealm.setDefaultLocale(rep.getDefaultLocale());
    }
    if (rep.getAttributes() != null) {
        for (Map.Entry<String, String> attr : rep.getAttributes().entrySet()) {
            newRealm.setAttribute(attr.getKey(), attr.getValue());
        }
    }
    if (newRealm.getComponentsStream(newRealm.getId(), KeyProvider.class.getName()).count() == 0) {
        if (rep.getPrivateKey() != null) {
            DefaultKeyProviders.createProviders(newRealm, rep.getPrivateKey(), rep.getCertificate());
        } else {
            DefaultKeyProviders.createProviders(newRealm);
        }
    }
}
Also used : KeyProvider(org.keycloak.keys.KeyProvider) OAuth2DeviceConfig(org.keycloak.models.OAuth2DeviceConfig) ScopeContainerModel(org.keycloak.models.ScopeContainerModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap) ScopeMappingRepresentation(org.keycloak.representations.idm.ScopeMappingRepresentation) GroupModel(org.keycloak.models.GroupModel) ClientScopeModel(org.keycloak.models.ClientScopeModel) RoleModel(org.keycloak.models.RoleModel) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) RequiredActionProviderRepresentation(org.keycloak.representations.idm.RequiredActionProviderRepresentation) RequiredActionProviderModel(org.keycloak.models.RequiredActionProviderModel) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) ClientModel(org.keycloak.models.ClientModel) WebAuthnPolicy(org.keycloak.models.WebAuthnPolicy) Map(java.util.Map) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap)

Example 4 with ComponentExportRepresentation

use of org.keycloak.representations.idm.ComponentExportRepresentation in project keycloak by keycloak.

the class RepresentationToModel method importComponents.

protected static void importComponents(RealmModel newRealm, MultivaluedHashMap<String, ComponentExportRepresentation> components, String parentId) {
    for (Map.Entry<String, List<ComponentExportRepresentation>> entry : components.entrySet()) {
        String providerType = entry.getKey();
        for (ComponentExportRepresentation compRep : entry.getValue()) {
            ComponentModel component = new ComponentModel();
            component.setId(compRep.getId());
            component.setName(compRep.getName());
            component.setConfig(compRep.getConfig());
            component.setProviderType(providerType);
            component.setProviderId(compRep.getProviderId());
            component.setSubType(compRep.getSubType());
            component.setParentId(parentId);
            component = newRealm.importComponentModel(component);
            if (compRep.getSubComponents() != null) {
                importComponents(newRealm, compRep.getSubComponents(), component.getId());
            }
        }
    }
}
Also used : ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) ComponentModel(org.keycloak.component.ComponentModel) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) Map(java.util.Map) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap)

Example 5 with ComponentExportRepresentation

use of org.keycloak.representations.idm.ComponentExportRepresentation in project keycloak by keycloak.

the class StripSecretsUtils method stripForExport.

public static RealmRepresentation stripForExport(KeycloakSession session, RealmRepresentation rep) {
    strip(rep);
    List<ClientRepresentation> clients = rep.getClients();
    if (clients != null) {
        for (ClientRepresentation c : clients) {
            strip(c);
        }
    }
    List<IdentityProviderRepresentation> providers = rep.getIdentityProviders();
    if (providers != null) {
        for (IdentityProviderRepresentation r : providers) {
            strip(r);
        }
    }
    MultivaluedHashMap<String, ComponentExportRepresentation> components = rep.getComponents();
    if (components != null) {
        for (Map.Entry<String, List<ComponentExportRepresentation>> ent : components.entrySet()) {
            for (ComponentExportRepresentation c : ent.getValue()) {
                strip(session, ent.getKey(), c);
            }
        }
    }
    List<UserRepresentation> users = rep.getUsers();
    if (users != null) {
        for (UserRepresentation u : users) {
            strip(u);
        }
    }
    users = rep.getFederatedUsers();
    if (users != null) {
        for (UserRepresentation u : users) {
            strip(u);
        }
    }
    return rep;
}
Also used : IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) List(java.util.List) Map(java.util.Map) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Aggregations

ComponentExportRepresentation (org.keycloak.representations.idm.ComponentExportRepresentation)7 MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)6 List (java.util.List)5 Map (java.util.Map)5 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 LinkedList (java.util.LinkedList)3 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)3 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)3 HashSet (java.util.HashSet)2 ClientModel (org.keycloak.models.ClientModel)2 ClientScopeModel (org.keycloak.models.ClientScopeModel)2 RoleModel (org.keycloak.models.RoleModel)2 ArtifactBindingUtils.computeArtifactBindingIdentifierString (org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString)2 IdentityProviderRepresentation (org.keycloak.representations.idm.IdentityProviderRepresentation)2 ScopeMappingRepresentation (org.keycloak.representations.idm.ScopeMappingRepresentation)2 JsonEncoding (com.fasterxml.jackson.core.JsonEncoding)1 JsonFactory (com.fasterxml.jackson.core.JsonFactory)1 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1