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

The following examples show how to use org.keycloak.representations.idm.RealmRepresentation#getId() . 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: KeycloakServer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void importRealm(RealmRepresentation rep) {
    KeycloakSession session = sessionFactory.create();;
    session.getTransactionManager().begin();

    try {
        RealmManager manager = new RealmManager(session);

        if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
            info("Not importing realm " + rep.getRealm() + " realm already exists");
            return;
        }

        if (manager.getRealmByName(rep.getRealm()) != null) {
            info("Not importing realm " + rep.getRealm() + " realm already exists");
            return;
        }
        RealmModel realm = manager.importRealm(rep);

        info("Imported realm " + realm.getName());

        session.getTransactionManager().commit();
    } finally {
        session.close();
    }
}
 
Example 2
Source File: PartialImportTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void initAdminEvents() {
    RealmRepresentation realmRep = RealmBuilder.edit(testRealmResource().toRepresentation()).testEventListener().build();
    realmId = realmRep.getId();
    realmRep.setDuplicateEmailsAllowed(false);
    adminClient.realm(realmRep.getRealm()).update(realmRep);

    piRep = new PartialImportRepresentation();
}
 
Example 3
Source File: AssertEvents.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Matcher<String> defaultRealmId() {
    return new TypeSafeMatcher<String>() {
        private String realmId;

        @Override
        protected boolean matchesSafely(String item) {
            return item.equals(getRealmId());
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(getRealmId());
        }

        private String getRealmId() {
            if (realmId == null) {
                RealmRepresentation realm = context.adminClient.realm(DEFAULT_REALM).toRepresentation();
                if (realm == null) {
                    throw new RuntimeException("Default user does not exist: " + DEFAULT_USERNAME + ". Make sure to add it to your test realm.");
                }
                realmId = realm.getId();
            }
            return realmId;
        }

    };
}
 
Example 4
Source File: KeycloakApplication.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void importRealm(RealmRepresentation rep, String from) {
    KeycloakSession session = sessionFactory.create();
    boolean exists = false;
    try {
        session.getTransactionManager().begin();

        try {
            RealmManager manager = new RealmManager(session);

            if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }

            if (manager.getRealmByName(rep.getRealm()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }
            if (!exists) {
                RealmModel realm = manager.importRealm(rep);
                ServicesLogger.LOGGER.importedRealm(realm.getName(), from);
            }
            session.getTransactionManager().commit();
        } catch (Throwable t) {
            session.getTransactionManager().rollback();
            if (!exists) {
                ServicesLogger.LOGGER.unableToImportRealm(t, rep.getRealm(), from);
            }
        }
    } finally {
        session.close();
    }
}
 
Example 5
Source File: QuarkusJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void importRealm(RealmRepresentation rep, String from) {
    KeycloakSession session = factory.create();
    boolean exists = false;
    try {
        session.getTransactionManager().begin();

        try {
            RealmManager manager = new RealmManager(session);

            if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }

            if (manager.getRealmByName(rep.getRealm()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }
            if (!exists) {
                RealmModel realm = manager.importRealm(rep);
                ServicesLogger.LOGGER.importedRealm(realm.getName(), from);
            }
            session.getTransactionManager().commit();
        } catch (Throwable t) {
            session.getTransactionManager().rollback();
            if (!exists) {
                ServicesLogger.LOGGER.unableToImportRealm(t, rep.getRealm(), from);
            }
        }
    } finally {
        session.close();
    }
}
 
Example 6
Source File: RealmTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void assertRealm(RealmRepresentation realm, RealmRepresentation storedRealm) {
    if (realm.getId() != null) {
        assertEquals(realm.getId(), storedRealm.getId());
    }
    if (realm.getRealm() != null) {
        assertEquals(realm.getRealm(), storedRealm.getRealm());
    }
    if (realm.isEnabled() != null) assertEquals(realm.isEnabled(), storedRealm.isEnabled());
    if (realm.isBruteForceProtected() != null) assertEquals(realm.isBruteForceProtected(), storedRealm.isBruteForceProtected());
    if (realm.getMaxFailureWaitSeconds() != null) assertEquals(realm.getMaxFailureWaitSeconds(), storedRealm.getMaxFailureWaitSeconds());
    if (realm.getMinimumQuickLoginWaitSeconds() != null) assertEquals(realm.getMinimumQuickLoginWaitSeconds(), storedRealm.getMinimumQuickLoginWaitSeconds());
    if (realm.getWaitIncrementSeconds() != null) assertEquals(realm.getWaitIncrementSeconds(), storedRealm.getWaitIncrementSeconds());
    if (realm.getQuickLoginCheckMilliSeconds() != null) assertEquals(realm.getQuickLoginCheckMilliSeconds(), storedRealm.getQuickLoginCheckMilliSeconds());
    if (realm.getMaxDeltaTimeSeconds() != null) assertEquals(realm.getMaxDeltaTimeSeconds(), storedRealm.getMaxDeltaTimeSeconds());
    if (realm.getFailureFactor() != null) assertEquals(realm.getFailureFactor(), storedRealm.getFailureFactor());
    if (realm.isRegistrationAllowed() != null) assertEquals(realm.isRegistrationAllowed(), storedRealm.isRegistrationAllowed());
    if (realm.isRegistrationEmailAsUsername() != null) assertEquals(realm.isRegistrationEmailAsUsername(), storedRealm.isRegistrationEmailAsUsername());
    if (realm.isRememberMe() != null) assertEquals(realm.isRememberMe(), storedRealm.isRememberMe());
    if (realm.isVerifyEmail() != null) assertEquals(realm.isVerifyEmail(), storedRealm.isVerifyEmail());
    if (realm.isLoginWithEmailAllowed() != null) assertEquals(realm.isLoginWithEmailAllowed(), storedRealm.isLoginWithEmailAllowed());
    if (realm.isDuplicateEmailsAllowed() != null) assertEquals(realm.isDuplicateEmailsAllowed(), storedRealm.isDuplicateEmailsAllowed());
    if (realm.isResetPasswordAllowed() != null) assertEquals(realm.isResetPasswordAllowed(), storedRealm.isResetPasswordAllowed());
    if (realm.isEditUsernameAllowed() != null) assertEquals(realm.isEditUsernameAllowed(), storedRealm.isEditUsernameAllowed());
    if (realm.getSslRequired() != null) assertEquals(realm.getSslRequired(), storedRealm.getSslRequired());
    if (realm.getAccessCodeLifespan() != null) assertEquals(realm.getAccessCodeLifespan(), storedRealm.getAccessCodeLifespan());
    if (realm.getAccessCodeLifespanUserAction() != null)
        assertEquals(realm.getAccessCodeLifespanUserAction(), storedRealm.getAccessCodeLifespanUserAction());
    if (realm.getActionTokenGeneratedByAdminLifespan() != null)
        assertEquals(realm.getActionTokenGeneratedByAdminLifespan(), storedRealm.getActionTokenGeneratedByAdminLifespan());
    if (realm.getActionTokenGeneratedByUserLifespan() != null)
        assertEquals(realm.getActionTokenGeneratedByUserLifespan(), storedRealm.getActionTokenGeneratedByUserLifespan());
    else
        assertEquals(realm.getAccessCodeLifespanUserAction(), storedRealm.getActionTokenGeneratedByUserLifespan());
    if (realm.getNotBefore() != null) assertEquals(realm.getNotBefore(), storedRealm.getNotBefore());
    if (realm.getAccessTokenLifespan() != null) assertEquals(realm.getAccessTokenLifespan(), storedRealm.getAccessTokenLifespan());
    if (realm.getAccessTokenLifespanForImplicitFlow() != null) assertEquals(realm.getAccessTokenLifespanForImplicitFlow(), storedRealm.getAccessTokenLifespanForImplicitFlow());
    if (realm.getSsoSessionIdleTimeout() != null) assertEquals(realm.getSsoSessionIdleTimeout(), storedRealm.getSsoSessionIdleTimeout());
    if (realm.getSsoSessionMaxLifespan() != null) assertEquals(realm.getSsoSessionMaxLifespan(), storedRealm.getSsoSessionMaxLifespan());
    if (realm.getSsoSessionIdleTimeoutRememberMe() != null) Assert.assertEquals(realm.getSsoSessionIdleTimeoutRememberMe(), storedRealm.getSsoSessionIdleTimeoutRememberMe());
    if (realm.getSsoSessionMaxLifespanRememberMe() != null) Assert.assertEquals(realm.getSsoSessionMaxLifespanRememberMe(), storedRealm.getSsoSessionMaxLifespanRememberMe());
    if (realm.getClientSessionIdleTimeout() != null)
        Assert.assertEquals(realm.getClientSessionIdleTimeout(), storedRealm.getClientSessionIdleTimeout());
    if (realm.getClientSessionMaxLifespan() != null)
        Assert.assertEquals(realm.getClientSessionMaxLifespan(), storedRealm.getClientSessionMaxLifespan());
    if (realm.getClientOfflineSessionIdleTimeout() != null)
        Assert.assertEquals(realm.getClientOfflineSessionIdleTimeout(), storedRealm.getClientOfflineSessionIdleTimeout());
    if (realm.getClientOfflineSessionMaxLifespan() != null)
        Assert.assertEquals(realm.getClientOfflineSessionMaxLifespan(), storedRealm.getClientOfflineSessionMaxLifespan());
    if (realm.getRequiredCredentials() != null) {
        assertNotNull(storedRealm.getRequiredCredentials());
        for (String cred : realm.getRequiredCredentials()) {
            assertTrue(storedRealm.getRequiredCredentials().contains(cred));
        }
    }
    if (realm.getLoginTheme() != null) assertEquals(realm.getLoginTheme(), storedRealm.getLoginTheme());
    if (realm.getAccountTheme() != null) assertEquals(realm.getAccountTheme(), storedRealm.getAccountTheme());
    if (realm.getAdminTheme() != null) assertEquals(realm.getAdminTheme(), storedRealm.getAdminTheme());
    if (realm.getEmailTheme() != null) assertEquals(realm.getEmailTheme(), storedRealm.getEmailTheme());

    if (realm.getPasswordPolicy() != null) assertEquals(realm.getPasswordPolicy(), storedRealm.getPasswordPolicy());

    if (realm.getDefaultRoles() != null) {
        assertNotNull(storedRealm.getDefaultRoles());
        for (String role : realm.getDefaultRoles()) {
            assertTrue(storedRealm.getDefaultRoles().contains(role));
        }
    }

    if (realm.getSmtpServer() != null) {
        assertEquals(realm.getSmtpServer(), storedRealm.getSmtpServer());
    }

    if (realm.getBrowserSecurityHeaders() != null) {
        assertEquals(realm.getBrowserSecurityHeaders(), storedRealm.getBrowserSecurityHeaders());
    }

    if (realm.getAttributes() != null) {
        HashMap<String, String> attributes = new HashMap<>();
        attributes.putAll(storedRealm.getAttributes());
        attributes.entrySet().retainAll(realm.getAttributes().entrySet());
        assertEquals(realm.getAttributes(), attributes);
    }

    if (realm.isUserManagedAccessAllowed() != null) assertEquals(realm.isUserManagedAccessAllowed(), storedRealm.isUserManagedAccessAllowed());
}
 
Example 7
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;
}