Search in sources :

Example 26 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class LDAPProvidersIntegrationTest method testLDAPUserRefreshCache.

@Test
public void testLDAPUserRefreshCache() {
    testingClient.server().run(session -> {
        session.userCache().clear();
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
        LDAPTestUtils.addLDAPUser(ldapProvider, appRealm, "johndirect", "John", "Direct", "johndirect@email.org", null, "1234");
        // Fetch user from LDAP and check that postalCode is filled
        UserModel user = session.users().getUserByUsername(appRealm, "johndirect");
        String postalCode = user.getFirstAttribute("postal_code");
        Assert.assertEquals("1234", postalCode);
        LDAPTestUtils.removeLDAPUserByUsername(ldapProvider, appRealm, ldapProvider.getLdapIdentityStore().getConfig(), "johndirect");
    });
    // 5 minutes in future, user should be cached still
    setTimeOffset(60 * 5);
    testingClient.server().run(session -> {
        RealmModel appRealm = new RealmManager(session).getRealmByName("test");
        CachedUserModel user = (CachedUserModel) session.users().getUserByUsername(appRealm, "johndirect");
        String postalCode = user.getFirstAttribute("postal_code");
        String email = user.getEmail();
        Assert.assertEquals("1234", postalCode);
        Assert.assertEquals("johndirect@email.org", email);
    });
    // 20 minutes into future, cache will be invalidated
    setTimeOffset(60 * 20);
    testingClient.server().run(session -> {
        RealmModel appRealm = new RealmManager(session).getRealmByName("test");
        UserModel user = session.users().getUserByUsername(appRealm, "johndirect");
        Assert.assertNull(user);
    });
    setTimeOffset(0);
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) CachedUserModel(org.keycloak.models.cache.CachedUserModel) RealmManager(org.keycloak.services.managers.RealmManager) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 27 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class FederatedStorageExportImportTest method testSingleFile.

@Test
public void testSingleFile() {
    ComponentExportImportTest.clearExportImportProperties(testingClient);
    final String userId = "f:1:path";
    testingClient.server().run(session -> {
        RealmModel realm = new RealmManager(session).createRealm(REALM_NAME);
        RoleModel role = realm.addRole("test-role");
        GroupModel group = realm.createGroup("test-group");
        List<String> attrValues = new LinkedList<>();
        attrValues.add("1");
        attrValues.add("2");
        session.userFederatedStorage().setSingleAttribute(realm, userId, "single1", "value1");
        session.userFederatedStorage().setAttribute(realm, userId, "list1", attrValues);
        session.userFederatedStorage().addRequiredAction(realm, userId, "UPDATE_PASSWORD");
        PasswordCredentialModel credential = FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).encodedCredential("password", realm.getPasswordPolicy().getHashIterations());
        session.userFederatedStorage().createCredential(realm, userId, credential);
        session.userFederatedStorage().grantRole(realm, userId, role);
        session.userFederatedStorage().joinGroup(realm, userId, group);
    });
    final String realmId = testRealmResource().toRepresentation().getId();
    final String groupId = testRealmResource().getGroupByPath("/test-group").getId();
    final String exportFileAbsolutePath = this.exportFileAbsolutePath;
    testingClient.server().run(session -> {
        ExportImportConfig.setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
        ExportImportConfig.setFile(exportFileAbsolutePath);
        ExportImportConfig.setRealmName(REALM_NAME);
        ExportImportConfig.setAction(ExportImportConfig.ACTION_EXPORT);
        new ExportImportManager(session).runExport();
        session.realms().removeRealm(realmId);
    });
    testingClient.server().run(session -> {
        Assert.assertNull(session.realms().getRealmByName(REALM_NAME));
        ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);
        new ExportImportManager(session).runImport();
    });
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(REALM_NAME);
        Assert.assertNotNull(realm);
        RoleModel role = realm.getRole("test-role");
        GroupModel group = realm.getGroupById(groupId);
        Assert.assertEquals(1, session.userFederatedStorage().getStoredUsersCount(realm));
        MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, userId);
        Assert.assertEquals(3, attributes.size());
        Assert.assertEquals("value1", attributes.getFirst("single1"));
        Assert.assertTrue(attributes.getList("list1").contains("1"));
        Assert.assertTrue(attributes.getList("list1").contains("2"));
        Assert.assertTrue(session.userFederatedStorage().getRequiredActionsStream(realm, userId).collect(Collectors.toSet()).contains("UPDATE_PASSWORD"));
        Assert.assertTrue(session.userFederatedStorage().getRoleMappingsStream(realm, userId).collect(Collectors.toSet()).contains(role));
        Assert.assertTrue(session.userFederatedStorage().getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group));
        List<CredentialModel> creds = session.userFederatedStorage().getStoredCredentialsStream(realm, userId).collect(Collectors.toList());
        Assert.assertEquals(1, creds.size());
        Assert.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).verify("password", PasswordCredentialModel.createFromCredentialModel(creds.get(0))));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CredentialModel(org.keycloak.credential.CredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) GroupModel(org.keycloak.models.GroupModel) ExportImportManager(org.keycloak.exportimport.ExportImportManager) RoleModel(org.keycloak.models.RoleModel) RealmManager(org.keycloak.services.managers.RealmManager) LinkedList(java.util.LinkedList) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 28 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class UserSessionPersisterProviderTest method testOnClientRemoved.

@Test
public void testOnClientRemoved() {
    int started = Time.currentTime();
    AtomicReference<String> userSessionID = new AtomicReference<>();
    inComittedTransaction(session -> {
        RealmModel fooRealm = session.realms().createRealm("foo", "foo");
        fooRealm.setDefaultRole(session.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX));
        fooRealm.addClient("foo-app");
        fooRealm.addClient("bar-app");
        session.users().addUser(fooRealm, "user3");
        UserSessionModel userSession = session.sessions().createUserSession(fooRealm, session.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
        userSessionID.set(userSession.getId());
        createClientSession(session, realmId, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
        createClientSession(session, realmId, fooRealm.getClientByClientId("bar-app"), userSession, "http://redirect", "state");
    });
    inComittedTransaction(session -> {
        RealmModel fooRealm = session.realms().getRealm("foo");
        // Persist offline session
        UserSessionModel userSession = session.sessions().getUserSession(fooRealm, userSessionID.get());
        persistUserSession(session, userSession, true);
    });
    inComittedTransaction(session -> {
        RealmManager realmMgr = new RealmManager(session);
        ClientManager clientMgr = new ClientManager(realmMgr);
        RealmModel fooRealm = realmMgr.getRealm("foo");
        // Assert session was persisted with both clientSessions
        UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
        assertSession(persistedSession, session.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app");
        // Remove foo-app client
        ClientModel client = fooRealm.getClientByClientId("foo-app");
        clientMgr.removeClient(fooRealm, client);
    });
    inComittedTransaction(session -> {
        RealmManager realmMgr = new RealmManager(session);
        ClientManager clientMgr = new ClientManager(realmMgr);
        RealmModel fooRealm = realmMgr.getRealm("foo");
        // Assert just one bar-app clientSession persisted now
        UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
        assertSession(persistedSession, session.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "bar-app");
        // Remove bar-app client
        ClientModel client = fooRealm.getClientByClientId("bar-app");
        clientMgr.removeClient(fooRealm, client);
    });
    inComittedTransaction(session -> {
        // Assert loading still works - last userSession is still there, but no clientSession on it
        loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        // Cleanup
        RealmManager realmMgr = new RealmManager(session);
        realmMgr.removeRealm(realmMgr.getRealm("foo"));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) ClientManager(org.keycloak.services.managers.ClientManager) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 29 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class OfflineSessionPersistenceTest method testPersistenceSingleNodeDeleteRealm.

@Test
public void testPersistenceSingleNodeDeleteRealm() {
    String realmId2 = inComittedTransaction(session -> {
        return prepareRealm(session, "realm2").getId();
    });
    List<String> userIds2 = withRealm(realmId2, (session, realm) -> IntStream.range(0, USER_COUNT).mapToObj(i -> session.users().addUser(realm, "user2-" + i)).map(UserModel::getId).collect(Collectors.toList()));
    try {
        List<String> offlineSessionIds = createOfflineSessions(realmId, userIds);
        assertOfflineSessionsExist(realmId, offlineSessionIds);
        List<String> offlineSessionIds2 = createOfflineSessions(realmId2, userIds2);
        assertOfflineSessionsExist(realmId2, offlineSessionIds2);
        // Simulate server restart
        reinitializeKeycloakSessionFactory();
        withRealm(realmId2, (session, realm) -> new RealmManager(session).removeRealm(realm));
        // Simulate server restart
        reinitializeKeycloakSessionFactory();
        assertOfflineSessionsExist(realmId, offlineSessionIds);
    } finally {
        withRealm(realmId2, (session, realm) -> realm == null ? false : new RealmManager(session).removeRealm(realm));
    }
}
Also used : ClientModel(org.keycloak.models.ClientModel) IntStream(java.util.stream.IntStream) UserSessionProvider(org.keycloak.models.UserSessionProvider) InfinispanUserSessionProviderFactory(org.keycloak.models.sessions.infinispan.InfinispanUserSessionProviderFactory) RealmManager(org.keycloak.services.managers.RealmManager) Constants(org.keycloak.models.Constants) Random(java.util.Random) UserModel(org.keycloak.models.UserModel) RealmProvider(org.keycloak.models.RealmProvider) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) Map(java.util.Map) RequireProvider(org.keycloak.testsuite.model.RequireProvider) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) LinkedList(java.util.LinkedList) RealmModel(org.keycloak.models.RealmModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) KeycloakSession(org.keycloak.models.KeycloakSession) Matchers(org.hamcrest.Matchers) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest) Test(org.junit.Test) UserSessionModel(org.keycloak.models.UserSessionModel) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) UserProvider(org.keycloak.models.UserProvider) List(java.util.List) Stream(java.util.stream.Stream) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) InfinispanUserSessionProvider(org.keycloak.models.sessions.infinispan.InfinispanUserSessionProvider) UserModel(org.keycloak.models.UserModel) RealmManager(org.keycloak.services.managers.RealmManager) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest) Test(org.junit.Test)

Example 30 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class UserSessionPersisterProviderTest method testOnRealmRemoved.

@Test
public void testOnRealmRemoved() {
    AtomicReference<String> userSessionID = new AtomicReference<>();
    inComittedTransaction(session -> {
        RealmModel fooRealm = session.realms().createRealm("foo", "foo");
        fooRealm.setDefaultRole(session.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
        fooRealm.addClient("foo-app");
        session.users().addUser(fooRealm, "user3");
        UserSessionModel userSession = session.sessions().createUserSession(fooRealm, session.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
        userSessionID.set(userSession.getId());
        createClientSession(session, realmId, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
    });
    inComittedTransaction(session -> {
        // Persist offline session
        RealmModel fooRealm = session.realms().getRealm("foo");
        UserSessionModel userSession = session.sessions().getUserSession(fooRealm, userSessionID.get());
        persistUserSession(session, userSession, true);
    });
    inComittedTransaction(session -> {
        // Assert session was persisted
        loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        // Remove realm
        RealmManager realmMgr = new RealmManager(session);
        realmMgr.removeRealm(realmMgr.getRealm("foo"));
    });
    inComittedTransaction(session -> {
        // Assert nothing loaded
        loadPersistedSessionsPaginated(session, true, 10, 0, 0);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Aggregations

RealmManager (org.keycloak.services.managers.RealmManager)47 RealmModel (org.keycloak.models.RealmModel)34 Test (org.junit.Test)19 UserModel (org.keycloak.models.UserModel)17 KeycloakSession (org.keycloak.models.KeycloakSession)16 ClientModel (org.keycloak.models.ClientModel)13 ClientManager (org.keycloak.services.managers.ClientManager)11 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)8 Path (javax.ws.rs.Path)6 UserSessionModel (org.keycloak.models.UserSessionModel)6 UserManager (org.keycloak.models.UserManager)5 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)4 LinkedList (java.util.LinkedList)3 GET (javax.ws.rs.GET)3 NotFoundException (javax.ws.rs.NotFoundException)3 Produces (javax.ws.rs.Produces)3 UserConsentModel (org.keycloak.models.UserConsentModel)3 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)3