Search in sources :

Example 81 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class KeycloakApplication method bootstrap.

// Bootstrap master realm, import realms and create admin user.
protected ExportImportManager bootstrap() {
    ExportImportManager[] exportImportManager = new ExportImportManager[1];
    logger.debug("bootstrap");
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            // TODO what is the purpose of following piece of code? Leaving it as is for now.
            JtaTransactionManagerLookup lookup = (JtaTransactionManagerLookup) sessionFactory.getProviderFactory(JtaTransactionManagerLookup.class);
            if (lookup != null) {
                if (lookup.getTransactionManager() != null) {
                    try {
                        Transaction transaction = lookup.getTransactionManager().getTransaction();
                        logger.debugv("bootstrap current transaction? {0}", transaction != null);
                        if (transaction != null) {
                            logger.debugv("bootstrap current transaction status? {0}", transaction.getStatus());
                        }
                    } catch (SystemException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            // TODO up here ^^
            ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
            exportImportManager[0] = new ExportImportManager(session);
            boolean createMasterRealm = applianceBootstrap.isNewInstall();
            if (exportImportManager[0].isRunImport() && exportImportManager[0].isImportMasterIncluded()) {
                createMasterRealm = false;
            }
            if (createMasterRealm) {
                applianceBootstrap.createMasterRealm();
            }
        }
    });
    if (exportImportManager[0].isRunImport()) {
        exportImportManager[0].runImport();
    } else {
        importRealms();
    }
    importAddUser();
    return exportImportManager[0];
}
Also used : ApplianceBootstrap(org.keycloak.services.managers.ApplianceBootstrap) JtaTransactionManagerLookup(org.keycloak.transaction.JtaTransactionManagerLookup) Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) ExportImportManager(org.keycloak.exportimport.ExportImportManager)

Example 82 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class KeycloakApplication method importAddUser.

public void importAddUser() {
    String configDir = System.getProperty("jboss.server.config.dir");
    if (configDir != null) {
        File addUserFile = new File(configDir + File.separator + "keycloak-add-user.json");
        if (addUserFile.isFile()) {
            ServicesLogger.LOGGER.imprtingUsersFrom(addUserFile);
            List<RealmRepresentation> realms;
            try {
                realms = JsonSerialization.readValue(new FileInputStream(addUserFile), new TypeReference<List<RealmRepresentation>>() {
                });
            } catch (IOException e) {
                ServicesLogger.LOGGER.failedToLoadUsers(e);
                return;
            }
            for (RealmRepresentation realmRep : realms) {
                for (UserRepresentation userRep : realmRep.getUsers()) {
                    KeycloakSession session = sessionFactory.create();
                    try {
                        session.getTransactionManager().begin();
                        RealmModel realm = session.realms().getRealmByName(realmRep.getRealm());
                        if (realm == null) {
                            ServicesLogger.LOGGER.addUserFailedRealmNotFound(userRep.getUsername(), realmRep.getRealm());
                        }
                        UserProvider users = session.users();
                        if (users.getUserByUsername(realm, userRep.getUsername()) != null) {
                            ServicesLogger.LOGGER.notCreatingExistingUser(userRep.getUsername());
                        } else {
                            UserModel user = users.addUser(realm, userRep.getUsername());
                            user.setEnabled(userRep.isEnabled());
                            RepresentationToModel.createCredentials(userRep, session, realm, user, false);
                            RepresentationToModel.createRoleMappings(userRep, user, realm);
                            ServicesLogger.LOGGER.addUserSuccess(userRep.getUsername(), realmRep.getRealm());
                        }
                        session.getTransactionManager().commit();
                    } catch (ModelDuplicateException e) {
                        session.getTransactionManager().rollback();
                        ServicesLogger.LOGGER.addUserFailedUserExists(userRep.getUsername(), realmRep.getRealm());
                    } catch (Throwable t) {
                        session.getTransactionManager().rollback();
                        ServicesLogger.LOGGER.addUserFailed(t, userRep.getUsername(), realmRep.getRealm());
                    } finally {
                        session.close();
                    }
                }
            }
            if (!addUserFile.delete()) {
                ServicesLogger.LOGGER.failedToDeleteFile(addUserFile.getAbsolutePath());
            }
        }
    }
}
Also used : RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserProvider(org.keycloak.models.UserProvider) KeycloakSession(org.keycloak.models.KeycloakSession) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) TypeReference(com.fasterxml.jackson.core.type.TypeReference) File(java.io.File) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 83 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class KeycloakApplication method setupScheduledTasks.

public static void setupScheduledTasks(final KeycloakSessionFactory sessionFactory) {
    long interval = Config.scope("scheduled").getLong("interval", 900L) * 1000;
    KeycloakSession session = sessionFactory.create();
    try {
        TimerProvider timer = session.getProvider(TimerProvider.class);
        timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredEvents(), interval), interval, "ClearExpiredEvents");
        timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredClientInitialAccessTokens(), interval), interval, "ClearExpiredClientInitialAccessTokens");
        timer.schedule(new ScheduledTaskRunner(sessionFactory, new ClearExpiredUserSessions()), interval, ClearExpiredUserSessions.TASK_NAME);
        new UserStorageSyncManager().bootstrapPeriodic(sessionFactory, timer);
    } finally {
        session.close();
    }
}
Also used : UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) ClusterAwareScheduledTaskRunner(org.keycloak.services.scheduled.ClusterAwareScheduledTaskRunner) ScheduledTaskRunner(org.keycloak.services.scheduled.ScheduledTaskRunner) KeycloakSession(org.keycloak.models.KeycloakSession) ClusterAwareScheduledTaskRunner(org.keycloak.services.scheduled.ClusterAwareScheduledTaskRunner) TimerProvider(org.keycloak.timer.TimerProvider) ClearExpiredEvents(org.keycloak.services.scheduled.ClearExpiredEvents) ClearExpiredClientInitialAccessTokens(org.keycloak.services.scheduled.ClearExpiredClientInitialAccessTokens) ClearExpiredUserSessions(org.keycloak.services.scheduled.ClearExpiredUserSessions)

Example 84 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class RestartCookieTest method testRestartCookieBackwardsCompatible_Keycloak25.

// KEYCLOAK-5440 -- migration from Keycloak 3.1.0
@Test
public void testRestartCookieBackwardsCompatible_Keycloak25() throws IOException {
    String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
        try {
            String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
            RealmModel realm = session.realms().getRealmByName("test");
            KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);
            String encodedToken = new JWSBuilder().kid(activeKey.getKid()).content(cookieVal.getBytes("UTF-8")).hmac256(activeKey.getSecretKey());
            return encodedToken;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });
    oauth.openLoginForm();
    driver.manage().deleteAllCookies();
    driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));
    loginPage.login("foo", "bar");
    loginPage.assertCurrent();
    Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
    events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails().detail(Details.RESTART_AFTER_TIMEOUT, "true").client((String) null).assertEvent();
}
Also used : RealmModel(org.keycloak.models.RealmModel) RestartLoginCookie(org.keycloak.protocol.RestartLoginCookie) Cookie(org.openqa.selenium.Cookie) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) KeyManager(org.keycloak.models.KeyManager) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 85 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class RestartCookieTest method testRestartCookieBackwardsCompatible_Keycloak19.

// KEYCLOAK-7158 -- migration from Keycloak 1.9.8
@Test
public void testRestartCookieBackwardsCompatible_Keycloak19() throws IOException {
    String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
        try {
            String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
            RealmModel realm = session.realms().getRealmByName("test");
            KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);
            // There was no KID in the token in Keycloak 1.9.8
            String encodedToken = new JWSBuilder().content(cookieVal.getBytes("UTF-8")).hmac256(activeKey.getSecretKey());
            return encodedToken;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });
    oauth.openLoginForm();
    driver.manage().deleteAllCookies();
    driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));
    loginPage.login("foo", "bar");
    loginPage.assertCurrent();
    Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
    events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails().detail(Details.RESTART_AFTER_TIMEOUT, "true").client((String) null).assertEvent();
}
Also used : RealmModel(org.keycloak.models.RealmModel) RestartLoginCookie(org.keycloak.protocol.RestartLoginCookie) Cookie(org.openqa.selenium.Cookie) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) KeyManager(org.keycloak.models.KeyManager) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

KeycloakSession (org.keycloak.models.KeycloakSession)189 RealmModel (org.keycloak.models.RealmModel)136 UserModel (org.keycloak.models.UserModel)78 Test (org.junit.Test)76 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)61 ClientModel (org.keycloak.models.ClientModel)58 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)53 List (java.util.List)34 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 Collectors (java.util.stream.Collectors)21 IOException (java.io.IOException)20 Map (java.util.Map)19 UserSessionModel (org.keycloak.models.UserSessionModel)19 ArrayList (java.util.ArrayList)18 ClientScopeModel (org.keycloak.models.ClientScopeModel)18 RoleModel (org.keycloak.models.RoleModel)18 Set (java.util.Set)16 RealmManager (org.keycloak.services.managers.RealmManager)16 HashMap (java.util.HashMap)14 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)14