Search in sources :

Example 31 with KeycloakSession

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

the class QuarkusKeycloakApplication method createAdminUser.

private void createAdminUser() {
    String adminUserName = System.getenv(KEYCLOAK_ADMIN_ENV_VAR);
    String adminPassword = System.getenv(KEYCLOAK_ADMIN_PASSWORD_ENV_VAR);
    if ((adminUserName == null || adminUserName.trim().length() == 0) || (adminPassword == null || adminPassword.trim().length() == 0)) {
        return;
    }
    KeycloakSessionFactory sessionFactory = KeycloakApplication.getSessionFactory();
    KeycloakSession session = sessionFactory.create();
    KeycloakTransactionManager transaction = session.getTransactionManager();
    try {
        transaction.begin();
        new ApplianceBootstrap(session).createMasterRealmUser(adminUserName, adminPassword);
        ServicesLogger.LOGGER.addUserSuccess(adminUserName, Config.getAdminRealm());
        transaction.commit();
    } catch (IllegalStateException e) {
        session.getTransactionManager().rollback();
        ServicesLogger.LOGGER.addUserFailedUserExists(adminUserName, Config.getAdminRealm());
    } catch (Throwable t) {
        session.getTransactionManager().rollback();
        ServicesLogger.LOGGER.addUserFailed(t, adminUserName, Config.getAdminRealm());
    } finally {
        session.close();
    }
}
Also used : ApplianceBootstrap(org.keycloak.services.managers.ApplianceBootstrap) KeycloakTransactionManager(org.keycloak.models.KeycloakTransactionManager) KeycloakSession(org.keycloak.models.KeycloakSession) QuarkusKeycloakSessionFactory(org.keycloak.quarkus.runtime.integration.QuarkusKeycloakSessionFactory) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory)

Example 32 with KeycloakSession

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

the class RepresentationToModel method toModel.

public static ResourceServer toModel(ResourceServerRepresentation rep, AuthorizationProvider authorization, ClientModel client) {
    ResourceServerStore resourceServerStore = authorization.getStoreFactory().getResourceServerStore();
    ResourceServer resourceServer;
    ResourceServer existing = resourceServerStore.findByClient(client);
    if (existing == null) {
        resourceServer = resourceServerStore.create(client);
        resourceServer.setAllowRemoteResourceManagement(true);
        resourceServer.setPolicyEnforcementMode(PolicyEnforcementMode.ENFORCING);
    } else {
        resourceServer = existing;
    }
    resourceServer.setPolicyEnforcementMode(rep.getPolicyEnforcementMode());
    resourceServer.setAllowRemoteResourceManagement(rep.isAllowRemoteResourceManagement());
    DecisionStrategy decisionStrategy = rep.getDecisionStrategy();
    if (decisionStrategy == null) {
        decisionStrategy = DecisionStrategy.UNANIMOUS;
    }
    resourceServer.setDecisionStrategy(decisionStrategy);
    for (ScopeRepresentation scope : rep.getScopes()) {
        toModel(scope, resourceServer, authorization);
    }
    KeycloakSession session = authorization.getKeycloakSession();
    RealmModel realm = authorization.getRealm();
    for (ResourceRepresentation resource : rep.getResources()) {
        ResourceOwnerRepresentation owner = resource.getOwner();
        if (owner == null) {
            owner = new ResourceOwnerRepresentation();
            owner.setId(resourceServer.getId());
            resource.setOwner(owner);
        } else if (owner.getName() != null) {
            UserModel user = session.users().getUserByUsername(realm, owner.getName());
            if (user != null) {
                owner.setId(user.getId());
            }
        }
        toModel(resource, resourceServer, authorization);
    }
    importPolicies(authorization, resourceServer, rep.getPolicies(), null);
    return resourceServer;
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) KeycloakSession(org.keycloak.models.KeycloakSession) DecisionStrategy(org.keycloak.representations.idm.authorization.DecisionStrategy) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) ResourceServer(org.keycloak.authorization.model.ResourceServer) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation)

Example 33 with KeycloakSession

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

the class KeycloakModelUtils method runJobInTransaction.

/**
 * Wrap given runnable job into KeycloakTransaction.
 *
 * @param factory
 * @param task
 */
public static void runJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task) {
    KeycloakSession session = factory.create();
    KeycloakTransaction tx = session.getTransactionManager();
    try {
        tx.begin();
        task.run(session);
        if (tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            } else {
                tx.commit();
            }
        }
    } catch (RuntimeException re) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw re;
    } finally {
        session.close();
    }
}
Also used : KeycloakSession(org.keycloak.models.KeycloakSession) KeycloakTransaction(org.keycloak.models.KeycloakTransaction)

Example 34 with KeycloakSession

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

the class UserConsentWithUserStorageModelTest method deleteClientScopeTest.

@Test
@ModelTest
public void deleteClientScopeTest(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesDelClScope1) -> {
        KeycloakSession currentSession = sesDelClScope1;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        ClientModel fooClient = realm.getClientByClientId("foo-client");
        ClientScopeModel fooScope = KeycloakModelUtils.getClientScopeByName(realm, "foo");
        realm.removeClientScope(fooScope.getId());
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesDelClScope2) -> {
        KeycloakSession currentSession = sesDelClScope2;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        ClientModel fooClient = realm.getClientByClientId("foo-client");
        UserModel john = currentSession.users().getUserByUsername(realm, "john");
        UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId());
        Assert.assertEquals(johnConsent.getGrantedClientScopes().size(), 0);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) ClientScopeModel(org.keycloak.models.ClientScopeModel) UserConsentModel(org.keycloak.models.UserConsentModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 35 with KeycloakSession

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

the class UserSessionProviderOfflineTest method testOfflineSessionsCrud.

@Test
@ModelTest
public void testOfflineSessionsCrud(KeycloakSession session) {
    Map<String, Set<String>> offlineSessions = new HashMap<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud) -> {
        // Create some online sessions in infinispan
        reloadState(sessionCrud);
        createSessions(sessionCrud);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud2) -> {
        currentSession = sessionCrud2;
        realm = currentSession.realms().getRealm("test");
        sessionManager = new UserSessionManager(currentSession);
        // Key is userSession ID, values are client UUIDS
        // Persist 3 created userSessions and clientSessions as offline
        ClientModel testApp = realm.getClientByClientId("test-app");
        currentSession.sessions().getUserSessionsStream(realm, testApp).collect(Collectors.toList()).forEach(userSession -> offlineSessions.put(userSession.getId(), createOfflineSessionIncludeClientSessions(currentSession, userSession)));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud3) -> {
        currentSession = sessionCrud3;
        realm = currentSession.realms().getRealm("test");
        sessionManager = new UserSessionManager(currentSession);
        // Assert all previously saved offline sessions found
        for (Map.Entry<String, Set<String>> entry : offlineSessions.entrySet()) {
            UserSessionModel offlineSession = sessionManager.findOfflineUserSession(realm, entry.getKey());
            Assert.assertNotNull(offlineSession);
            Assert.assertEquals(offlineSession.getAuthenticatedClientSessions().keySet(), entry.getValue());
        }
        // Find clients with offline token
        UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
        Set<ClientModel> clients = sessionManager.findClientsWithOfflineToken(realm, user1);
        Assert.assertEquals(clients.size(), 2);
        for (ClientModel client : clients) {
            Assert.assertTrue(client.getClientId().equals("test-app") || client.getClientId().equals("third-party"));
        }
        UserModel user2 = currentSession.users().getUserByUsername(realm, "user2");
        clients = sessionManager.findClientsWithOfflineToken(realm, user2);
        Assert.assertEquals(clients.size(), 1);
        Assert.assertEquals("test-app", clients.iterator().next().getClientId());
        // Test count
        ClientModel testApp = realm.getClientByClientId("test-app");
        ClientModel thirdparty = realm.getClientByClientId("third-party");
        Assert.assertEquals(3, currentSession.sessions().getOfflineSessionsCount(realm, testApp));
        Assert.assertEquals(1, currentSession.sessions().getOfflineSessionsCount(realm, thirdparty));
        // Revoke "test-app" for user1
        sessionManager.revokeOfflineToken(user1, testApp);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud4) -> {
        currentSession = sessionCrud4;
        realm = currentSession.realms().getRealm("test");
        sessionManager = new UserSessionManager(currentSession);
        // Assert userSession revoked
        ClientModel thirdparty = realm.getClientByClientId("third-party");
        List<UserSessionModel> thirdpartySessions = currentSession.sessions().getOfflineUserSessionsStream(realm, thirdparty, 0, 10).collect(Collectors.toList());
        Assert.assertEquals(1, thirdpartySessions.size());
        Assert.assertEquals("127.0.0.1", thirdpartySessions.get(0).getIpAddress());
        Assert.assertEquals("user1", thirdpartySessions.get(0).getUser().getUsername());
        UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
        UserModel user2 = currentSession.users().getUserByUsername(realm, "user2");
        Set<ClientModel> clients = sessionManager.findClientsWithOfflineToken(realm, user1);
        Assert.assertEquals(1, clients.size());
        Assert.assertEquals("third-party", clients.iterator().next().getClientId());
        clients = sessionManager.findClientsWithOfflineToken(realm, user2);
        Assert.assertEquals(1, clients.size());
        Assert.assertEquals("test-app", clients.iterator().next().getClientId());
        // Revoke the second currentSession for user1 too.
        sessionManager.revokeOfflineToken(user1, thirdparty);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud5) -> {
        currentSession = sessionCrud5;
        realm = currentSession.realms().getRealm("test");
        sessionManager = new UserSessionManager(currentSession);
        ClientModel testApp = realm.getClientByClientId("test-app");
        ClientModel thirdparty = realm.getClientByClientId("third-party");
        // Accurate count now. All sessions of user1 cleared
        Assert.assertEquals(1, currentSession.sessions().getOfflineSessionsCount(realm, testApp));
        Assert.assertEquals(0, currentSession.sessions().getOfflineSessionsCount(realm, thirdparty));
        List<UserSessionModel> testAppSessions = currentSession.sessions().getOfflineUserSessionsStream(realm, testApp, 0, 10).collect(Collectors.toList());
        Assert.assertEquals(1, testAppSessions.size());
        Assert.assertEquals("127.0.0.3", testAppSessions.get(0).getIpAddress());
        Assert.assertEquals("user2", testAppSessions.get(0).getUser().getUsername());
        UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
        Set<ClientModel> clients = sessionManager.findClientsWithOfflineToken(realm, user1);
        Assert.assertEquals(0, clients.size());
    });
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) UserSessionManager(org.keycloak.services.managers.UserSessionManager) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) HashMap(java.util.HashMap) Map(java.util.Map) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) 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