Search in sources :

Example 86 with KeycloakSession

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

the class ClientPoliciesUtil method getValidatedGlobalClientProfilesRepresentation.

/**
 * get validated and modified global (built-in) client profiles set on keycloak app as representation.
 * it is loaded from json file enclosed in keycloak's binary.
 * not return null.
 */
static List<ClientProfileRepresentation> getValidatedGlobalClientProfilesRepresentation(KeycloakSession session, InputStream is) throws ClientPolicyException {
    // load builtin client profiles representation
    ClientProfilesRepresentation proposedProfilesRep = null;
    try {
        proposedProfilesRep = JsonSerialization.readValue(is, ClientProfilesRepresentation.class);
    } catch (Exception e) {
        throw new ClientPolicyException("failed to deserialize global proposed client profiles json string.", e.getMessage());
    }
    if (proposedProfilesRep == null) {
        return Collections.emptyList();
    }
    // no profile contained (it is valid)
    List<ClientProfileRepresentation> proposedProfileRepList = proposedProfilesRep.getProfiles();
    if (proposedProfileRepList == null || proposedProfileRepList.isEmpty()) {
        return Collections.emptyList();
    }
    // duplicated profile name is not allowed.
    if (proposedProfileRepList.size() != proposedProfileRepList.stream().map(i -> i.getName()).distinct().count()) {
        throw new ClientPolicyException("proposed global client profile name duplicated.");
    }
    // construct validated and modified profiles from builtin profiles in JSON file enclosed in keycloak binary.
    List<ClientProfileRepresentation> updatingProfileList = new LinkedList<>();
    for (ClientProfileRepresentation proposedProfileRep : proposedProfilesRep.getProfiles()) {
        if (proposedProfileRep.getName() == null) {
            throw new ClientPolicyException("client profile without its name not allowed.");
        }
        ClientProfileRepresentation profileRep = new ClientProfileRepresentation();
        profileRep.setName(proposedProfileRep.getName());
        profileRep.setDescription(proposedProfileRep.getDescription());
        // to prevent returning null
        profileRep.setExecutors(new ArrayList<>());
        if (proposedProfileRep.getExecutors() != null) {
            for (ClientPolicyExecutorRepresentation executorRep : proposedProfileRep.getExecutors()) {
                // Skip the check if feature is disabled as then the executor implementations are disabled
                if (Profile.isFeatureEnabled(Profile.Feature.CLIENT_POLICIES) && !isValidExecutor(session, executorRep.getExecutorProviderId())) {
                    throw new ClientPolicyException("proposed client profile contains the executor with its invalid configuration.");
                }
                profileRep.getExecutors().add(executorRep);
            }
        }
        updatingProfileList.add(profileRep);
    }
    return updatingProfileList;
}
Also used : ClientPoliciesRepresentation(org.keycloak.representations.idm.ClientPoliciesRepresentation) ClientProfilesRepresentation(org.keycloak.representations.idm.ClientProfilesRepresentation) Profile(org.keycloak.common.Profile) Logger(org.jboss.logging.Logger) Constants(org.keycloak.models.Constants) ArrayList(java.util.ArrayList) ComponentModel(org.keycloak.component.ComponentModel) ClientPolicyConditionConfigurationRepresentation(org.keycloak.representations.idm.ClientPolicyConditionConfigurationRepresentation) JsonNode(com.fasterxml.jackson.databind.JsonNode) LinkedList(java.util.LinkedList) ClientPolicyConditionProvider(org.keycloak.services.clientpolicy.condition.ClientPolicyConditionProvider) ClientPolicyExecutorProvider(org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorProvider) ClientPolicyConditionRepresentation(org.keycloak.representations.idm.ClientPolicyConditionRepresentation) ClientPolicyRepresentation(org.keycloak.representations.idm.ClientPolicyRepresentation) ClientPolicyExecutorConfigurationRepresentation(org.keycloak.representations.idm.ClientPolicyExecutorConfigurationRepresentation) RealmModel(org.keycloak.models.RealmModel) Set(java.util.Set) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) JsonConfigComponentModel(org.keycloak.component.JsonConfigComponentModel) ClientPolicyExecutorRepresentation(org.keycloak.representations.idm.ClientPolicyExecutorRepresentation) ClientProfileRepresentation(org.keycloak.representations.idm.ClientProfileRepresentation) JsonSerialization(org.keycloak.util.JsonSerialization) List(java.util.List) Collections(java.util.Collections) InputStream(java.io.InputStream) ClientProfileRepresentation(org.keycloak.representations.idm.ClientProfileRepresentation) ClientPolicyExecutorRepresentation(org.keycloak.representations.idm.ClientPolicyExecutorRepresentation) ClientProfilesRepresentation(org.keycloak.representations.idm.ClientProfilesRepresentation) IOException(java.io.IOException) LinkedList(java.util.LinkedList)

Example 87 with KeycloakSession

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

the class ClientStorageTest method testRefreshWithOfflineToken.

private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken offlineToken, String offlineTokenString, final String sessionId, String userId) {
    // Change offset to big value to ensure userSession expired
    setTimeOffset(99999);
    Assert.assertFalse(oldToken.isActive());
    Assert.assertTrue(offlineToken.isActive());
    // Assert userSession expired
    testingClient.testing().removeExpired("test");
    try {
        testingClient.testing().removeUserSession("test", sessionId);
    } catch (NotFoundException nfe) {
    // Ignore
    }
    OAuthClient.AccessTokenResponse response = oauth.doRefreshTokenRequest(offlineTokenString, "password");
    AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken());
    String offlineUserSessionId = testingClient.server().fetch((KeycloakSession session) -> session.sessions().getOfflineUserSession(session.realms().getRealmByName("test"), offlineToken.getSessionState()).getId(), String.class);
    Assert.assertEquals(200, response.getStatusCode());
    Assert.assertEquals(offlineUserSessionId, refreshedToken.getSessionState());
    // Assert new refreshToken in the response
    String newRefreshToken = response.getRefreshToken();
    Assert.assertNotNull(newRefreshToken);
    Assert.assertNotEquals(oldToken.getId(), refreshedToken.getId());
    Assert.assertEquals(userId, refreshedToken.getSubject());
    Assert.assertTrue(refreshedToken.getRealmAccess().isUserInRole(Constants.OFFLINE_ACCESS_ROLE));
    EventRepresentation refreshEvent = events.expectRefresh(offlineToken.getId(), sessionId).client("hardcoded-client").user(userId).removeDetail(Details.UPDATED_REFRESH_TOKEN_ID).detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE).assertEvent();
    Assert.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID));
    setTimeOffset(0);
    return newRefreshToken;
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) KeycloakSession(org.keycloak.models.KeycloakSession) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) NotFoundException(javax.ws.rs.NotFoundException)

Example 88 with KeycloakSession

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

the class OfflineSessionPersistenceTest method createEnvironment.

@Override
public void createEnvironment(KeycloakSession s) {
    RealmModel realm = prepareRealm(s, "realm");
    this.realmId = realm.getId();
    userIds = IntStream.range(0, USER_COUNT).mapToObj(i -> s.users().addUser(realm, "user-" + i)).map(UserModel::getId).collect(Collectors.toList());
}
Also used : RealmModel(org.keycloak.models.RealmModel) 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)

Example 89 with KeycloakSession

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

the class UserSyncTest method createEnvironment.

@Override
public void createEnvironment(KeycloakSession s) {
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().createRealm("realm");
        realm.setDefaultRole(session.roles().addRealmRole(realm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm.getName()));
        this.realmId = realm.getId();
    });
    getParameters(UserStorageProviderModel.class).forEach(fs -> inComittedTransaction(session -> {
        if (userFederationId != null || !fs.isImportEnabled())
            return;
        RealmModel realm = session.realms().getRealm(realmId);
        fs.setParentId(realmId);
        ComponentModel res = realm.addComponentModel(fs);
        // Check if the provider implements ImportSynchronization interface
        UserStorageProviderFactory userStorageProviderFactory = (UserStorageProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, res.getProviderId());
        if (!ImportSynchronization.class.isAssignableFrom(userStorageProviderFactory.getClass())) {
            return;
        }
        userFederationId = res.getId();
        log.infof("Added %s user federation provider: %s", fs.getName(), res.getId());
    }));
    assumeThat("Cannot run UserSyncTest because there is no user federation provider that supports sync", userFederationId, notNullValue());
}
Also used : RealmModel(org.keycloak.models.RealmModel) IntStream(java.util.stream.IntStream) CoreMatchers.is(org.hamcrest.CoreMatchers.is) RealmModel(org.keycloak.models.RealmModel) Assume.assumeThat(org.junit.Assume.assumeThat) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) UserStorageProvider(org.keycloak.storage.UserStorageProvider) LDAPTestUtils(org.keycloak.testsuite.util.LDAPTestUtils) Constants(org.keycloak.models.Constants) Matchers(org.hamcrest.Matchers) KeycloakSession(org.keycloak.models.KeycloakSession) Test(org.junit.Test) LDAPStorageProviderFactory(org.keycloak.storage.ldap.LDAPStorageProviderFactory) UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) ClusterProvider(org.keycloak.cluster.ClusterProvider) UserProvider(org.keycloak.models.UserProvider) ImportSynchronization(org.keycloak.storage.user.ImportSynchronization) RealmProvider(org.keycloak.models.RealmProvider) ComponentModel(org.keycloak.component.ComponentModel) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) UserStorageProviderFactory(org.keycloak.storage.UserStorageProviderFactory) UserStorageProviderFactory(org.keycloak.storage.UserStorageProviderFactory) ComponentModel(org.keycloak.component.ComponentModel) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel)

Example 90 with KeycloakSession

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

the class DBLockTest method simpleNestedLockTest.

@Test
public void simpleNestedLockTest() throws Exception {
    inComittedTransaction(1, (session, i) -> {
        // first session lock DATABASE
        DBLockProvider dbLock1 = new DBLockManager(session).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());
        return null;
    });
}
Also used : KeycloakSession(org.keycloak.models.KeycloakSession) DBLockManager(org.keycloak.models.dblock.DBLockManager) DBLockProvider(org.keycloak.models.dblock.DBLockProvider) Test(org.junit.Test)

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