Java Code Examples for org.keycloak.models.utils.KeycloakModelUtils#runJobInTransaction()

The following examples show how to use org.keycloak.models.utils.KeycloakModelUtils#runJobInTransaction() . 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: AbstractUserSessionClusterListener.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void eventReceived(ClusterEvent event) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, (KeycloakSession session) -> {
        InfinispanUserSessionProvider provider = (InfinispanUserSessionProvider) session.getProvider(UserSessionProvider.class, InfinispanUserSessionProviderFactory.PROVIDER_ID);
        SE sessionEvent = (SE) event;

        boolean shouldResendEvent = shouldResendEvent(session, sessionEvent);

        if (log.isDebugEnabled()) {
            log.debugf("Received user session event '%s'. Should resend event: %b", sessionEvent.toString(), shouldResendEvent);
        }

        eventReceived(session, provider, sessionEvent);

        if (shouldResendEvent) {
            session.getProvider(ClusterProvider.class).notify(sessionEvent.getEventKey(), event, true, ClusterProvider.DCNotify.ALL_BUT_LOCAL_DC);
        }

    });
}
 
Example 2
Source File: UserStorageSyncManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Check federationProviderModel of all realms and possibly start periodic sync for them
 *
 * @param sessionFactory
 * @param timer
 */
public void bootstrapPeriodic(final KeycloakSessionFactory sessionFactory, final TimerProvider timer) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            List<RealmModel> realms = session.realms().getRealmsWithProviderType(UserStorageProvider.class);
            for (final RealmModel realm : realms) {
                List<UserStorageProviderModel> providers = realm.getUserStorageProviders();
                for (final UserStorageProviderModel provider : providers) {
                    UserStorageProviderFactory factory = (UserStorageProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, provider.getProviderId());
                    if (factory instanceof ImportSynchronization && provider.isImportEnabled()) {
                        refreshPeriodicSyncForProvider(sessionFactory, timer, provider, realm.getId());
                    }
                }
            }

            ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
            clusterProvider.registerListener(USER_STORAGE_TASK_KEY, new UserStorageClusterListener(sessionFactory));
        }
    });
}
 
Example 3
Source File: LDAPStorageProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 *  !! This function must be called from try-with-resources block, otherwise Vault secrets may be leaked !!
 * @param sessionFactory
 * @param realmId
 * @param model
 * @return
 */
private LDAPQuery createQuery(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel model) {
    class QueryHolder {
        LDAPQuery query;
    }

    final QueryHolder queryHolder = new QueryHolder();
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            session.getContext().setRealm(session.realms().getRealm(realmId));

            LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider)session.getProvider(UserStorageProvider.class, model);
            RealmModel realm = session.realms().getRealm(realmId);
            queryHolder.query = LDAPUtils.createQueryForUserSearch(ldapFedProvider, realm);
        }

    });
    return queryHolder.query;
}
 
Example 4
Source File: AuthenticationSessionProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void setAccessCodeLifespan(KeycloakSession session, int lifespan, int lifespanUserAction, int lifespanLogin) {

        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionLifespan) -> {
            KeycloakSession currentSession = sessionLifespan;
            RealmModel realm = currentSession.realms().getRealm("test");

            if (lifespan != -1)
                realm.setAccessCodeLifespan(lifespan);

            if (lifespanUserAction != -1)
                realm.setAccessCodeLifespanUserAction(lifespanUserAction);

            if (lifespanLogin != -1)
                realm.setAccessCodeLifespanLogin(lifespanLogin);
        });
    }
 
Example 5
Source File: LDAPStorageProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void syncMappers(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel model) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            RealmModel realm = session.realms().getRealm(realmId);
            session.getContext().setRealm(realm);
            session.getProvider(UserStorageProvider.class, model);
            List<ComponentModel> mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
            for (ComponentModel mapperModel : mappers) {
                LDAPStorageMapper ldapMapper = session.getProvider(LDAPStorageMapper.class, mapperModel);
                SynchronizationResult syncResult = ldapMapper.syncDataFromFederationProviderToKeycloak(realm);
                if (syncResult.getAdded() > 0 || syncResult.getUpdated() > 0 || syncResult.getRemoved() > 0 || syncResult.getFailed() > 0) {
                    logger.infof("Sync of federation mapper '%s' finished. Status: %s", mapperModel.getName(), syncResult.toString());
                }
            }
        }

    });
}
 
Example 6
Source File: SingleFileExportProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void exportModel(KeycloakSessionFactory factory) throws IOException {
    logger.infof("Exporting model into file %s", this.file.getAbsolutePath());
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            List<RealmModel> realms = session.realms().getRealms();
            List<RealmRepresentation> reps = new ArrayList<>();
            for (RealmModel realm : realms) {
                reps.add(ExportUtils.exportRealm(session, realm, true, true));
            }

            writeToFile(reps);
        }

    });

}
 
Example 7
Source File: SingleFileImportProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void importModel(KeycloakSessionFactory factory, final Strategy strategy) throws IOException {
    logger.infof("Full importing from file %s", this.file.getAbsolutePath());
    checkRealmReps();

    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            ImportUtils.importRealms(session, realmReps.values(), strategy);
        }

    });
}
 
Example 8
Source File: SingleFileExportProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void exportRealm(KeycloakSessionFactory factory, final String realmName) throws IOException {
    logger.infof("Exporting realm '%s' into file %s", realmName, this.file.getAbsolutePath());
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            RealmModel realm = session.realms().getRealmByName(realmName);
            RealmRepresentation realmRep = ExportUtils.exportRealm(session, realm, true, true);
            writeToFile(realmRep);
        }

    });
}
 
Example 9
Source File: DBLockTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void testTwoLocksCurrently(KeycloakSession session) throws Exception {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionLC) -> {
        testTwoLocksCurrentlyInternal(sessionLC, DBLockProvider.Namespace.DATABASE, DBLockProvider.Namespace.OFFLINE_SESSIONS);
    });
}
 
Example 10
Source File: DBLockTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void testTwoNestedLocksCurrently(KeycloakSession session) throws Exception {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionLC) -> {
        testTwoNestedLocksCurrentlyInternal(sessionLC, DBLockProvider.Namespace.KEYCLOAK_BOOT, DBLockProvider.Namespace.DATABASE);
    });
}
 
Example 11
Source File: UserConsentWithUserStorageModelTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void getAllConsentTest(KeycloakSession session) {

    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSessionACT) -> {
        KeycloakSession currentSession = currentSessionACT;
        RealmModel realm = currentSession.realms().getRealmByName("original");

        ClientModel fooClient = realm.getClientByClientId("foo-client");

        UserModel john = currentSessionACT.users().getUserByUsername("john", realm);
        UserModel mary = currentSessionACT.users().getUserByUsername("mary", realm);

        List<UserConsentModel> johnConsents = currentSession.users().getConsents(realm, john.getId());
        Assert.assertEquals(2, johnConsents.size());

        ClientModel hardcodedClient = currentSessionACT.realms().getClientByClientId("hardcoded-client", realm);

        List<UserConsentModel> maryConsents = currentSession.users().getConsents(realm, mary.getId());
        Assert.assertEquals(2, maryConsents.size());
        UserConsentModel maryConsent = maryConsents.get(0);
        UserConsentModel maryHardcodedConsent = maryConsents.get(1);
        if (maryConsents.get(0).getClient().getId().equals(hardcodedClient.getId())) {
            maryConsent = maryConsents.get(1);
            maryHardcodedConsent = maryConsents.get(0);

        }
        Assert.assertEquals(maryConsent.getClient().getId(), fooClient.getId());
        Assert.assertEquals(maryConsent.getGrantedClientScopes().size(), 1);
        Assert.assertTrue(isClientScopeGranted(realm, "foo", maryConsent));

        Assert.assertEquals(maryHardcodedConsent.getClient().getId(), hardcodedClient.getId());
        Assert.assertEquals(maryHardcodedConsent.getGrantedClientScopes().size(), 0);
    });
}
 
Example 12
Source File: ClientModelTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void json(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionJson) -> {
        currentSession = sessionJson;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);

        client = setUpClient(realm);
        ClientRepresentation representation = ModelToRepresentation.toRepresentation(client, currentSession);
        representation.setId(null);
        for (ProtocolMapperRepresentation protocolMapper : representation.getProtocolMappers()) {
            protocolMapper.setId(null);
        }

        realm = currentSession.realms().createRealm("copy");
        ClientModel copyClient = RepresentationToModel.createClient(currentSession, realm, representation, true);

        assertEquals(client, copyClient);

        client.unregisterNode("node1");
        client.unregisterNode("10.20.30.40");

        currentSession.realms().removeClient(client.getId(), realm);
        currentSession.realms().removeClient(copyClient.getId(), realm);
        currentSession.realms().removeRealm(realm.getId());
    });
}
 
Example 13
Source File: UserSessionPersisterProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void testNoSessions(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionNS) -> {
        UserSessionPersisterProvider persister = sessionNS.getProvider(UserSessionPersisterProvider.class);
        List<UserSessionModel> sessions = persister.loadUserSessions(0, 1, true, 0, "abc");
        Assert.assertEquals(0, sessions.size());
    });
}
 
Example 14
Source File: UserStorageSyncManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public SynchronizationResult syncAllUsers(final KeycloakSessionFactory sessionFactory, final String realmId, final UserStorageProviderModel provider) {
    UserStorageProviderFactory factory = (UserStorageProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, provider.getProviderId());
    if (!(factory instanceof ImportSynchronization) || !provider.isImportEnabled() || !provider.isEnabled()) {
        return SynchronizationResult.ignored();

    }

    final Holder holder = new Holder();

    // Ensure not executed concurrently on this or any other cluster node
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
            // shared key for "full" and "changed" . Improve if needed
            String taskKey = provider.getId() + "::sync";

            // 30 seconds minimal timeout for now
            int timeout = Math.max(30, provider.getFullSyncPeriod());
            holder.result = clusterProvider.executeIfNotExecuted(taskKey, timeout, new Callable<SynchronizationResult>() {

                @Override
                public SynchronizationResult call() throws Exception {
                    updateLastSyncInterval(sessionFactory, provider, realmId);
                    return ((ImportSynchronization)factory).sync(sessionFactory, realmId, provider);
                }

            });
        }

    });

    if (holder.result == null || !holder.result.isExecuted()) {
        logger.debugf("syncAllUsers for federation provider %s was ignored as it's already in progress", provider.getName());
        return SynchronizationResult.ignored();
    } else {
        return holder.result.getResult();
    }
}
 
Example 15
Source File: DBLockTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void simpleNestedLockTest(KeycloakSession session) throws Exception {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionLC) -> {
        // first session lock DATABASE
        DBLockProvider dbLock1 = new DBLockManager(sessionLC).getDBLock();
        dbLock1.waitForLock(DBLockProvider.Namespace.DATABASE);
        try {
            Assert.assertEquals(DBLockProvider.Namespace.DATABASE, dbLock1.getCurrentLock());
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionLC2) -> {
                // a second session/dblock-provider can lock another namespace OFFLINE_SESSIONS
                DBLockProvider dbLock2 = new DBLockManager(sessionLC2).getDBLock();
                dbLock2.waitForLock(DBLockProvider.Namespace.OFFLINE_SESSIONS);
                try {
                    // getCurrentLock is local, each provider instance has one
                    Assert.assertEquals(DBLockProvider.Namespace.OFFLINE_SESSIONS, dbLock2.getCurrentLock());
                } finally {
                    dbLock2.releaseLock();
                }
                Assert.assertNull(dbLock2.getCurrentLock());
            });
        } finally {
            dbLock1.releaseLock();
        }
        Assert.assertNull(dbLock1.getCurrentLock());
    });
}
 
Example 16
Source File: LdapManyGroupsInitializerCommand.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void doRunCommand(KeycloakSession session) {
    String realmName = getArg(0);
    String groupsDn = getArg(1);
    int startOffsetTopGroups = getIntArg(2);
    int topGroupsCount = getIntArg(3);
    int subgroupsInEveryGroup = getIntArg(4);

    RealmModel realm = session.realms().getRealmByName(realmName);
    List<ComponentModel> components = realm.getComponents(realm.getId(), UserStorageProvider.class.getName());
    if (components.size() != 1) {
        log.errorf("Expected 1 LDAP Provider, but found: %d providers", components.size());
        throw new HandledException();
    }
    ComponentModel ldapModel = components.get(0);

    // Check that street mapper exists. It's required for now, so that "street" attribute is written to the LDAP
    ComponentModel groupMapperModel = getMapperModel(realm, ldapModel, "groupsMapper");


    // Create groups
    for (int i=startOffsetTopGroups ; i<startOffsetTopGroups+topGroupsCount ; i++) {
        final int iFinal = i;
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {

            LDAPStorageProvider ldapProvider = (LDAPStorageProvider)session.getProvider(UserStorageProvider.class, ldapModel);
            RealmModel appRealm = session.realms().getRealmByName(realmName);
            GroupLDAPStorageMapper groupMapper = (GroupLDAPStorageMapper) session.getProvider(LDAPStorageMapper.class, groupMapperModel);

            Set<String> childGroupDns = new HashSet<>();

            for (int j=0 ; j<subgroupsInEveryGroup ; j++) {
                String groupName = "group-" + iFinal + "-" + j;
                LDAPObject createdGroup = groupMapper.createLDAPGroup(groupName, new HashMap<>());
                childGroupDns.add(createdGroup.getDn().toString());
            }

            String topGroupName = "group-" + iFinal;

            Map<String, Set<String>> groupAttrs = new HashMap<>();
            groupAttrs.put("member", new HashSet<>(childGroupDns));

            groupMapper.createLDAPGroup(topGroupName, groupAttrs);

        });
    }
}
 
Example 17
Source File: UserConsentModelTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void setupEnv(KeycloakSession session) {

        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionEnv) -> {
            KeycloakSession currentSession = sessionEnv;

            RealmManager realmManager = new RealmManager(currentSession);
            RealmModel realm = realmManager.createRealm("original");

            ClientModel fooClient = realm.addClient("foo-client");
            ClientModel barClient = realm.addClient("bar-client");

            ClientScopeModel fooScope = realm.addClientScope("foo");
            fooScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

            ClientScopeModel barScope = realm.addClientScope("bar");
            fooScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

            UserModel john = currentSession.users().addUser(realm, "john");
            UserModel mary = currentSession.users().addUser(realm, "mary");

            UserConsentModel johnFooGrant = new UserConsentModel(fooClient);
            johnFooGrant.addGrantedClientScope(fooScope);
            realmManager.getSession().users().addConsent(realm, john.getId(), johnFooGrant);

            UserConsentModel johnBarGrant = new UserConsentModel(barClient);
            johnBarGrant.addGrantedClientScope(barScope);

            // Update should fail as grant doesn't yet exists
            try {
                realmManager.getSession().users().updateConsent(realm, john.getId(), johnBarGrant);
                Assert.fail("Not expected to end here");
            } catch (ModelException expected) {
            }

            realmManager.getSession().users().addConsent(realm, john.getId(), johnBarGrant);

            UserConsentModel maryFooGrant = new UserConsentModel(fooClient);
            maryFooGrant.addGrantedClientScope(fooScope);
            realmManager.getSession().users().addConsent(realm, mary.getId(), maryFooGrant);

            ClientStorageProviderModel clientStorage = new ClientStorageProviderModel();
            clientStorage.setProviderId(HardcodedClientStorageProviderFactory.PROVIDER_ID);
            clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.CLIENT_ID, "hardcoded-client");
            clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.REDIRECT_URI, "http://localhost:8081/*");
            clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.CONSENT, "true");
            clientStorage.setParentId(realm.getId());
            clientStorageComponent = realm.addComponentModel(clientStorage);

            ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);

            Assert.assertNotNull(hardcodedClient);

            UserConsentModel maryHardcodedGrant = new UserConsentModel(hardcodedClient);
            realmManager.getSession().users().addConsent(realm, mary.getId(), maryHardcodedGrant);
        });
    }
 
Example 18
Source File: UserConsentWithUserStorageModelTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void setupEnv(KeycloakSession session) {

        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionSetUpEnv) -> {
            KeycloakSession currentSession = sessionSetUpEnv;

            RealmManager realmManager = new RealmManager(currentSession);
            RealmModel realm = realmManager.createRealm("original");

            UserStorageProviderModel model = new UserStorageProviderModel();
            model.setName("memory");
            model.setPriority(0);
            model.setProviderId(UserMapStorageFactory.PROVIDER_ID);
            model.setParentId(realm.getId());
            model.getConfig().putSingle(IMPORT_ENABLED, Boolean.toString(false));
            realm.addComponentModel(model);

            ClientModel fooClient = realm.addClient("foo-client");
            ClientModel barClient = realm.addClient("bar-client");

            ClientScopeModel fooScope = realm.addClientScope("foo");
            fooScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

            ClientScopeModel barScope = realm.addClientScope("bar");
            fooScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

            UserModel john = currentSession.users().addUser(realm, "john");
            UserModel mary = currentSession.users().addUser(realm, "mary");

            UserConsentModel johnFooGrant = new UserConsentModel(fooClient);
            johnFooGrant.addGrantedClientScope(fooScope);
            realmManager.getSession().users().addConsent(realm, john.getId(), johnFooGrant);

            UserConsentModel johnBarGrant = new UserConsentModel(barClient);
            johnBarGrant.addGrantedClientScope(barScope);

            // Update should fail as grant doesn't yet exists
            try {
                currentSession.users().updateConsent(realm, john.getId(), johnBarGrant);
                Assert.fail("Not expected to end here");
            } catch (ModelException expected) {
            }

            realmManager.getSession().users().addConsent(realm, john.getId(), johnBarGrant);

            UserConsentModel maryFooGrant = new UserConsentModel(fooClient);
            maryFooGrant.addGrantedClientScope(fooScope);
            realmManager.getSession().users().addConsent(realm, mary.getId(), maryFooGrant);

            ClientStorageProviderModel clientStorage = new ClientStorageProviderModel();
            clientStorage.setProviderId(HardcodedClientStorageProviderFactory.PROVIDER_ID);
            clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.CLIENT_ID, "hardcoded-client");
            clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.REDIRECT_URI, "http://localhost:8081/*");
            clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.CONSENT, "true");
            clientStorage.setParentId(realm.getId());
            clientStorageComponent = realm.addComponentModel(clientStorage);

            ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);

            Assert.assertNotNull(hardcodedClient);

            UserConsentModel maryHardcodedGrant = new UserConsentModel(hardcodedClient);
            realmManager.getSession().users().addConsent(realm, mary.getId(), maryHardcodedGrant);
        });
    }
 
Example 19
Source File: UserConsentWithUserStorageModelTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@ModelTest
public void basicConsentTest(KeycloakSession session) {

    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSessionCT) -> {
        KeycloakSession currentSession = currentSessionCT;
        RealmModel realm = currentSession.realms().getRealmByName("original");

        ClientModel fooClient = realm.getClientByClientId("foo-client");
        ClientModel barClient = realm.getClientByClientId("bar-client");

        UserModel john = currentSessionCT.users().getUserByUsername("john", realm);
        UserModel mary = currentSessionCT.users().getUserByUsername("mary", realm);

        UserConsentModel johnFooConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId());
        Assert.assertEquals(johnFooConsent.getGrantedClientScopes().size(), 1);
        Assert.assertTrue(isClientScopeGranted(realm, "foo", johnFooConsent));
        Assert.assertNotNull("Created Date should be set", johnFooConsent.getCreatedDate());
        Assert.assertNotNull("Last Updated Date should be set", johnFooConsent.getLastUpdatedDate());

        UserConsentModel johnBarConsent = currentSession.users().getConsentByClient(realm, john.getId(), barClient.getId());
        Assert.assertEquals(johnBarConsent.getGrantedClientScopes().size(), 1);
        Assert.assertTrue(isClientScopeGranted(realm, "bar", johnBarConsent));
        Assert.assertNotNull("Created Date should be set", johnBarConsent.getCreatedDate());
        Assert.assertNotNull("Last Updated Date should be set", johnBarConsent.getLastUpdatedDate());

        UserConsentModel maryConsent = currentSession.users().getConsentByClient(realm, mary.getId(), fooClient.getId());
        Assert.assertEquals(maryConsent.getGrantedClientScopes().size(), 1);
        Assert.assertTrue(isClientScopeGranted(realm, "foo", maryConsent));
        Assert.assertNotNull("Created Date should be set", maryConsent.getCreatedDate());
        Assert.assertNotNull("Last Updated Date should be set", maryConsent.getLastUpdatedDate());

        ClientModel hardcodedClient = currentSessionCT.realms().getClientByClientId("hardcoded-client", realm);
        UserConsentModel maryHardcodedConsent = currentSession.users().getConsentByClient(realm, mary.getId(), hardcodedClient.getId());
        Assert.assertEquals(maryHardcodedConsent.getGrantedClientScopes().size(), 0);
        Assert.assertNotNull("Created Date should be set", maryHardcodedConsent.getCreatedDate());
        Assert.assertNotNull("Last Updated Date should be set", maryHardcodedConsent.getLastUpdatedDate());

        Assert.assertNull(currentSession.users().getConsentByClient(realm, mary.getId(), barClient.getId()));
        Assert.assertNull(currentSession.users().getConsentByClient(realm, john.getId(), hardcodedClient.getId()));
    });
}
 
Example 20
Source File: UserModelTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@ModelTest
public void webOriginSetTest(KeycloakSession session) {

    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesWebOrigin) -> {
        KeycloakSession currentSession = sesWebOrigin;
        RealmModel realm = currentSession.realms().getRealmByName("original");

        ClientModel client = realm.addClient("user");

        Assert.assertThat(client.getWebOrigins(), empty());

        client.addWebOrigin("origin-1");
        Assert.assertThat(client.getWebOrigins(), hasSize(1));

        client.addWebOrigin("origin-2");
        Assert.assertThat(client.getWebOrigins(), hasSize(2));

        client.removeWebOrigin("origin-2");
        Assert.assertThat(client.getWebOrigins(), hasSize(1));

        client.removeWebOrigin("origin-1");
        Assert.assertThat(client.getWebOrigins(), empty());

        client = realm.addClient("oauthclient2");

        Assert.assertThat(client.getWebOrigins(), empty());

        client.addWebOrigin("origin-1");
        Assert.assertThat(client.getWebOrigins(), hasSize(1));

        client.addWebOrigin("origin-2");
        Assert.assertThat(client.getWebOrigins(), hasSize(2));

        client.removeWebOrigin("origin-2");
        Assert.assertThat(client.getWebOrigins(), hasSize(1));

        client.removeWebOrigin("origin-1");
        Assert.assertThat(client.getWebOrigins(), empty());
    });
}