Package org.keycloak.models

Examples of org.keycloak.models.KeycloakSession


        }

        if (export || importt) {
            String exportImportProviderId = ExportImportConfig.getProvider();
            logger.debug("Will use provider: " + exportImportProviderId);
            KeycloakSession session = sessionFactory.create();

            try {
                if (export) {
                    ExportProvider exportProvider = session.getProvider(ExportProvider.class, exportImportProviderId);

                    if (realmName == null) {
                        logger.info("Full model export requested");
                        exportProvider.exportModel(sessionFactory);
                    } else {
                        logger.infof("Export of realm '%s' requested", realmName);
                        exportProvider.exportRealm(sessionFactory, realmName);
                    }
                    logger.info("Export finished successfully");
                } else {
                    ImportProvider importProvider = session.getProvider(ImportProvider.class, exportImportProviderId);
                    Strategy strategy = ExportImportConfig.getStrategy();
                    if (realmName == null) {
                        logger.infof("Full model import requested. Strategy: %s", strategy.toString());
                        importProvider.importModel(sessionFactory, strategy);
                    } else {
                        logger.infof("Import of realm '%s' requested. Strategy: %s", realmName, strategy.toString());
                        importProvider.importRealm(sessionFactory, realmName, strategy);
                    }
                    logger.info("Import finished successfully");
                }
            } catch (Throwable ioe) {
                logger.error("Error during export/import", ioe);
            } finally {
                session.close();
            }
        }
    }
View Full Code Here


    @Override
    protected void setupDefaultRealm(String contextPath) {
        super.setupDefaultRealm(contextPath);

        KeycloakSession session = sessionFactory.create();
        session.getTransaction().begin();

        // disable master realm by deleting the admin user.
        try {
            RealmManager manager = new RealmManager(session);
            RealmModel master = manager.getKeycloakAdminstrationRealm();
            UserModel admin = session.users().getUserByUsername("admin", master);
            if (admin != null) session.users().removeUser(master, admin);
            session.getTransaction().commit();
        } finally {
            session.close();
        }

    }
View Full Code Here

    @Override
    protected void setupDefaultRealm(String contextPath) {
        super.setupDefaultRealm(contextPath);

        ProviderSession providerSession = providerSessionFactory.createSession();
        KeycloakSession session = providerSession.getProvider(KeycloakSession.class);
        session.getTransaction().begin();

        // disable master realm by deleting the admin user.
        try {
            RealmManager manager = new RealmManager(session);
            RealmModel master = manager.getKeycloakAdminstrationRealm();
            UserModel admin = master.getUser("admin");
            if (admin != null) master.removeUser(admin.getLoginName());
            session.getTransaction().commit();
        } finally {
            providerSession.close();
        }

    }
View Full Code Here

        URI grantUri = OpenIDConnectService.grantAccessTokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);

        {   // test checkSsl
            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                realm.setSslRequired(SslRequired.ALL);
                session.getTransaction().commit();
                session.close();
            }

            Response response = executeGrantAccessTokenRequest(grantTarget);
            Assert.assertEquals(403, response.getStatus());
            response.close();

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                realm.setSslRequired(SslRequired.EXTERNAL);
                session.getTransaction().commit();
                session.close();
            }

        }

        {   // test null username
            String header = BasicAuthHelper.createHeader("test-app", "password");
            Form form = new Form();
            form.param("password", "password");
            Response response = grantTarget.request()
                    .header(HttpHeaders.AUTHORIZATION, header)
                    .post(Entity.form(form));
            Assert.assertEquals(401, response.getStatus());
            response.close();
        }

        {   // test no password
            String header = BasicAuthHelper.createHeader("test-app", "password");
            Form form = new Form();
            form.param("username", "test-user@localhost");
            Response response = grantTarget.request()
                    .header(HttpHeaders.AUTHORIZATION, header)
                    .post(Entity.form(form));
            Assert.assertEquals(400, response.getStatus());
            response.close();
        }

        {   // test bearer-only

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                ApplicationModel clientModel = realm.getApplicationByName("test-app");
                clientModel.setBearerOnly(true);
                session.getTransaction().commit();
                session.close();
            }


            Response response = executeGrantAccessTokenRequest(grantTarget);
            Assert.assertEquals(400, response.getStatus());
            response.close();

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                ApplicationModel clientModel = realm.getApplicationByName("test-app");
                clientModel.setBearerOnly(false);
                session.getTransaction().commit();
                session.close();
            }

        }

        {   // test realm disabled
            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                realm.setEnabled(false);
                session.getTransaction().commit();
                session.close();
            }

            Response response = executeGrantAccessTokenRequest(grantTarget);
            Assert.assertEquals(401, response.getStatus());
            response.close();

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                realm.setEnabled(true);
                session.getTransaction().commit();
                session.close();
            }

        }

        {   // test application disabled

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                ClientModel clientModel = realm.findClient("test-app");
                clientModel.setEnabled(false);
                session.getTransaction().commit();
                session.close();
            }


            Response response = executeGrantAccessTokenRequest(grantTarget);
            Assert.assertEquals(400, response.getStatus());
            response.close();

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                ClientModel clientModel = realm.findClient("test-app");
                clientModel.setEnabled(true);
                session.getTransaction().commit();
                session.close();
            }

        }

        {   // test user action required

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                UserModel user = session.users().getUserByUsername("test-user@localhost", realm);
                user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
                session.getTransaction().commit();
                session.close();
            }


            Response response = executeGrantAccessTokenRequest(grantTarget);
            Assert.assertEquals(400, response.getStatus());
            response.close();

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                UserModel user = session.users().getUserByUsername("test-user@localhost", realm);
                user.removeRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
                session.getTransaction().commit();
                session.close();
            }

        }
        {   // test user disabled
            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                UserModel user = session.users().getUserByUsername("test-user@localhost", realm);
                user.setEnabled(false);
                session.getTransaction().commit();
                session.close();
            }


            Response response = executeGrantAccessTokenRequest(grantTarget);
            Assert.assertEquals(400, response.getStatus());
            response.close();

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                UserModel user = session.users().getUserByUsername("test-user@localhost", realm);
                user.setEnabled(true);
                session.getTransaction().commit();
                session.close();
            }

        }

View Full Code Here

        this.task = task;
    }

    @Override
    public void run() {
        KeycloakSession session = sessionFactory.create();
        try {
            session.getTransaction().begin();
            task.run(session);
            session.getTransaction().commit();

            logger.debug("Executed scheduled task " + task.getClass().getSimpleName());
        } catch (Throwable t) {
            logger.error("Failed to run scheduled task " + task.getClass().getSimpleName(), t);

            session.getTransaction().rollback();
        } finally {
            try {
                session.close();
            } catch (Throwable t) {
                logger.error("Failed to close ProviderSession", t);
            }
        }
    }
View Full Code Here

        events.poll();

        String refreshId = oauth.verifyRefreshToken(tokenResponse.getRefreshToken()).getId();

        KeycloakSession session = keycloakRule.startSession();
        RealmModel realm = session.realms().getRealmByName("test");
        UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
        int last = userSession.getLastSessionRefresh();
        session.getTransaction().commit();
        session.close();

        Thread.sleep(2000);

        tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");

        AccessToken refreshedToken = oauth.verifyToken(tokenResponse.getAccessToken());
        RefreshToken refreshedRefreshToken = oauth.verifyRefreshToken(tokenResponse.getRefreshToken());

        Assert.assertEquals(200, tokenResponse.getStatusCode());

        session = keycloakRule.startSession();
        realm = session.realms().getRealmByName("test");
        userSession = session.sessions().getUserSession(realm, sessionId);
        int next = userSession.getLastSessionRefresh();
        session.getTransaction().commit();
        session.close();

        Assert.assertNotEquals(last, next);

        session = keycloakRule.startSession();
        realm = session.realms().getRealmByName("test");
        int lastAccessTokenLifespan = realm.getAccessTokenLifespan();
        realm.setAccessTokenLifespan(100000);
        session.getTransaction().commit();
        session.close();

        Thread.sleep(2000);
        tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");

        session = keycloakRule.startSession();
        realm = session.realms().getRealmByName("test");
        userSession = session.sessions().getUserSession(realm, sessionId);
        next = userSession.getLastSessionRefresh();
        session.getTransaction().commit();
        session.close();

        // lastSEssionRefresh should be updated because access code lifespan is higher than sso idle timeout
        Assert.assertThat(next, allOf(greaterThan(last), lessThan(last + 6)));

        session = keycloakRule.startSession();
        realm = session.realms().getRealmByName("test");
        int originalIdle = realm.getSsoSessionIdleTimeout();
        realm.setSsoSessionIdleTimeout(1);
        session.getTransaction().commit();
        session.close();

        events.clear();
        Thread.sleep(2000);
        tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");

        // test idle timeout
        assertEquals(400, tokenResponse.getStatusCode());
        assertNull(tokenResponse.getAccessToken());
        assertNull(tokenResponse.getRefreshToken());

        events.expectRefresh(refreshId, sessionId).error(Errors.INVALID_TOKEN);

        session = keycloakRule.startSession();
        realm = session.realms().getRealmByName("test");
        realm.setSsoSessionIdleTimeout(originalIdle);
        realm.setAccessTokenLifespan(lastAccessTokenLifespan);
        session.getTransaction().commit();
        session.close();

        events.clear();
    }
View Full Code Here

        events.poll();

        String refreshId = oauth.verifyRefreshToken(tokenResponse.getRefreshToken()).getId();

        KeycloakSession session = keycloakRule.startSession();
        RealmModel realm = session.realms().getRealmByName("test");
        int maxLifespan = realm.getSsoSessionMaxLifespan();
        realm.setSsoSessionMaxLifespan(1);
        session.getTransaction().commit();
        session.close();

        Thread.sleep(1000);

        tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");

        assertEquals(400, tokenResponse.getStatusCode());
        assertNull(tokenResponse.getAccessToken());
        assertNull(tokenResponse.getRefreshToken());

        session = keycloakRule.startSession();
        realm = session.realms().getRealmByName("test");
        realm.setSsoSessionMaxLifespan(maxLifespan);
        session.getTransaction().commit();
        session.close();


        events.expectRefresh(refreshId, sessionId).error(Errors.INVALID_TOKEN);

        events.clear();
View Full Code Here

            response.close();
        }

        {   // test checkSsl
            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                realm.setSslRequired(SslRequired.ALL);
                session.getTransaction().commit();
                session.close();
            }

            Response response = executeRefreshToken(refreshTarget, refreshToken);
            Assert.assertEquals(403, response.getStatus());
            response.close();

            {
                KeycloakSession session = keycloakRule.startSession();
                RealmModel realm = session.realms().getRealmByName("test");
                realm.setSslRequired(SslRequired.EXTERNAL);
                session.getTransaction().commit();
                session.close();
            }

        }

        {
View Full Code Here

        // Restart server, which triggers export
        keycloakRule.restartServer();

        // Delete some realm (and some data in admin realm)
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmProvider realmProvider = session.realms();
            UserProvider userProvider = session.users();
            new RealmManager(session).removeRealm(realmProvider.getRealmByName("test"));
            Assert.assertEquals(2, realmProvider.getRealms().size());

            assertNotAuthenticated(userProvider, realmProvider, "test", "test-user@localhost", "password");
            assertNotAuthenticated(userProvider, realmProvider, "test", "user1", "password");
            assertNotAuthenticated(userProvider, realmProvider, "test", "user2", "password");
            assertNotAuthenticated(userProvider, realmProvider, "test", "user3", "password");
        } finally {
            keycloakRule.stopSession(session, true);
        }

        // Configure import
        ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);

        // Restart server, which triggers import
        keycloakRule.restartServer();

        // Ensure data are imported back
        session = keycloakRule.startSession();
        try {
            RealmProvider model = session.realms();
            UserProvider userProvider = session.users();
            Assert.assertEquals(3, model.getRealms().size());

            assertAuthenticated(userProvider, model, "test", "test-user@localhost", "password");
            assertAuthenticated(userProvider, model, "test", "user1", "password");
            assertAuthenticated(userProvider, model, "test", "user2", "password");
View Full Code Here

        // Restart server, which triggers export
        keycloakRule.restartServer();

        // Delete some realm (and some data in admin realm)
        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmProvider realmProvider = session.realms();
            UserProvider userProvider = session.users();
            new RealmManager(session).removeRealm(realmProvider.getRealmByName("test"));
            Assert.assertEquals(2, realmProvider.getRealms().size());

            assertNotAuthenticated(userProvider, realmProvider, "test", "test-user@localhost", "password");
            assertNotAuthenticated(userProvider, realmProvider, "test", "user1", "password");
            assertNotAuthenticated(userProvider, realmProvider, "test", "user2", "password");
            assertNotAuthenticated(userProvider, realmProvider, "test", "user3", "password");
        } finally {
            keycloakRule.stopSession(session, true);
        }

        // Configure import
        ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);

        // Restart server, which triggers import
        keycloakRule.restartServer();

        // Ensure data are imported back, but just for "test" realm
        session = keycloakRule.startSession();
        try {
            RealmProvider realmProvider = session.realms();
            UserProvider userProvider = session.users();
            Assert.assertEquals(3, realmProvider.getRealms().size());

            assertAuthenticated(userProvider, realmProvider, "test", "test-user@localhost", "password");
            assertAuthenticated(userProvider, realmProvider, "test", "user1", "password");
            assertAuthenticated(userProvider, realmProvider, "test", "user2", "password");
View Full Code Here

TOP

Related Classes of org.keycloak.models.KeycloakSession

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.