Search in sources :

Example 16 with ClientScopeModel

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

the class ClientModelTest method testClientScopesBinding.

@Test
@ModelTest
public void testClientScopesBinding(KeycloakSession session) {
    AtomicReference<ClientScopeModel> scope1Atomic = new AtomicReference<>();
    AtomicReference<ClientScopeModel> scope2Atomic = new AtomicReference<>();
    AtomicReference<ClientScopeModel> scope3Atomic = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionClientScopeBind1) -> {
        currentSession = sessionClientScopeBind1;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.addClient("templatized");
        client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        ClientScopeModel scope1 = realm.addClientScope("scope1");
        scope1.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        scope1Atomic.set(scope1);
        ClientScopeModel scope2 = realm.addClientScope("scope2");
        scope2.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        scope2Atomic.set(scope2);
        ClientScopeModel scope3 = realm.addClientScope("scope3");
        scope3.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        scope3Atomic.set(scope3);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionClientScopeBind2) -> {
        currentSession = sessionClientScopeBind2;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.getClientByClientId("templatized");
        ClientScopeModel scope1 = scope1Atomic.get();
        ClientScopeModel scope2 = scope2Atomic.get();
        ClientScopeModel scope3 = scope3Atomic.get();
        scope1 = realm.getClientScopeById(scope1.getId());
        scope2 = realm.getClientScopeById(scope2.getId());
        scope3 = realm.getClientScopeById(scope3.getId());
        client.addClientScope(scope1, true);
        client.addClientScope(scope2, false);
        client.addClientScope(scope3, false);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionClientScopeBind3) -> {
        currentSession = sessionClientScopeBind3;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.getClientByClientId("templatized");
        ClientScopeModel scope1 = scope1Atomic.get();
        ClientScopeModel scope2 = scope2Atomic.get();
        Map<String, ClientScopeModel> clientScopes1 = client.getClientScopes(true);
        assertThat("Client Scope contains 'scope1':", clientScopes1.containsKey("scope1"), is(true));
        assertThat("Client Scope contains 'scope2':", clientScopes1.containsKey("scope2"), is(false));
        assertThat("Client Scope contains 'scope3':", clientScopes1.containsKey("scope3"), is(false));
        Map<String, ClientScopeModel> clientScopes2 = client.getClientScopes(false);
        assertThat("Client Scope contains 'scope1':", clientScopes2.containsKey("scope1"), is(false));
        assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(true));
        assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true));
        // Remove some binding and check it was removed
        client.removeClientScope(scope1);
        client.removeClientScope(scope2);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionClientScopeBind3) -> {
        currentSession = sessionClientScopeBind3;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.getClientByClientId("templatized");
        ClientScopeModel scope3 = scope3Atomic.get();
        Map<String, ClientScopeModel> clientScopes1 = client.getClientScopes(true);
        assertThat("Client Scope contains 'scope1':", clientScopes1.containsKey("scope1"), is(false));
        assertThat("Client Scope contains 'scope2':", clientScopes1.containsKey("scope2"), is(false));
        assertThat("Client Scope contains 'scope3':", clientScopes1.containsKey("scope3"), is(false));
        Map<String, ClientScopeModel> clientScopes2 = client.getClientScopes(false);
        assertThat("Client Scope contains 'scope1':", clientScopes2.containsKey("scope1"), is(false));
        assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(false));
        assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true));
        currentSession.clients().removeClient(realm, client.getId());
        client.removeClientScope(scope3);
        realm.removeClientScope(scope1Atomic.get().getId());
        realm.removeClientScope(scope2Atomic.get().getId());
        realm.removeClientScope(scope3Atomic.get().getId());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) KeycloakSession(org.keycloak.models.KeycloakSession) ClientScopeModel(org.keycloak.models.ClientScopeModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 17 with ClientScopeModel

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

the class MapClientScopeProvider method removeClientScope.

@Override
public boolean removeClientScope(RealmModel realm, String id) {
    if (id == null)
        return false;
    ClientScopeModel clientScope = getClientScopeById(realm, id);
    if (clientScope == null)
        return false;
    session.users().preRemove(clientScope);
    realm.removeDefaultClientScope(clientScope);
    session.getKeycloakSessionFactory().publish(new ClientScopeModel.ClientScopeRemovedEvent() {

        @Override
        public KeycloakSession getKeycloakSession() {
            return session;
        }

        @Override
        public ClientScopeModel getClientScope() {
            return clientScope;
        }
    });
    tx.delete(id);
    return true;
}
Also used : KeycloakSession(org.keycloak.models.KeycloakSession) ClientScopeModel(org.keycloak.models.ClientScopeModel)

Example 18 with ClientScopeModel

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

the class MigrateTo4_0_0 method migrateRealm.

protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean json) {
    // Upgrade names of clientScopes to not contain space
    realm.getClientScopesStream().filter(clientScope -> clientScope.getName().contains(" ")).forEach(clientScope -> {
        LOG.debugf("Replacing spaces with underscores in the name of client scope '%s' of realm '%s'", clientScope.getName(), realm.getName());
        String replacedName = clientScope.getName().replaceAll(" ", "_");
        clientScope.setName(replacedName);
    });
    if (!json) {
        // Add default client scopes. But don't add them to existing clients. For JSON, they were already added
        LOG.debugf("Adding defaultClientScopes for realm '%s'", realm.getName());
        DefaultClientScopes.createDefaultClientScopes(session, realm, false);
    }
    // Upgrade configuration of "allowed-client-templates" client registration policy
    realm.getComponentsStream(realm.getId(), "org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy").filter(component -> Objects.equals(component.getProviderId(), "allowed-client-templates")).forEach(component -> {
        List<String> configVal = component.getConfig().remove("allowed-client-templates");
        if (configVal != null) {
            component.getConfig().put("allowed-client-scopes", configVal);
        }
        component.put("allow-default-scopes", true);
        realm.updateComponent(component);
    });
    // If client has scope for offline_access role (either directly or through fullScopeAllowed), then add offline_access client
    // scope as optional scope to the client. If it's indirectly (no fullScopeAllowed), then remove role from the scoped roles
    RoleModel offlineAccessRole = realm.getRole(OAuth2Constants.OFFLINE_ACCESS);
    ClientScopeModel offlineAccessScope;
    if (offlineAccessRole == null) {
        LOG.infof("Role 'offline_access' not available in realm '%s'. Skip migration of offline_access client scope.", realm.getName());
    } else {
        offlineAccessScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
        if (offlineAccessScope == null) {
            LOG.infof("Client scope 'offline_access' not available in realm '%s'. Skip migration of offline_access client scope.", realm.getName());
        } else {
            realm.getClientsStream().filter(MigrationUtils::isOIDCNonBearerOnlyClient).filter(c -> c.hasScope(offlineAccessRole)).filter(c -> !c.getClientScopes(false).containsKey(OAuth2Constants.OFFLINE_ACCESS)).peek(c -> {
                LOG.debugf("Adding client scope 'offline_access' as optional scope to client '%s' in realm '%s'.", c.getClientId(), realm.getName());
                c.addClientScope(offlineAccessScope, false);
            }).filter(c -> !c.isFullScopeAllowed()).forEach(c -> {
                LOG.debugf("Removing role scope mapping for role 'offline_access' from client '%s' in realm '%s'.", c.getClientId(), realm.getName());
                c.deleteScopeMapping(offlineAccessRole);
            });
        }
    }
    // Clients with consentRequired, which don't have any client scopes will be added itself to require consent, so that consent screen is shown when users authenticate
    realm.getClientsStream().filter(ClientModel::isConsentRequired).filter(c -> c.getClientScopes(true).isEmpty()).forEach(c -> {
        LOG.debugf("Adding client '%s' of realm '%s' to display itself on consent screen", c.getClientId(), realm.getName());
        c.setDisplayOnConsentScreen(true);
        String consentText = c.getName() == null ? c.getClientId() : c.getName();
        c.setConsentScreenText(consentText);
    });
}
Also used : ClientModel(org.keycloak.models.ClientModel) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) Objects(java.util.Objects) List(java.util.List) DefaultClientScopes(org.keycloak.models.utils.DefaultClientScopes) ModelVersion(org.keycloak.migration.ModelVersion) OAuth2Constants(org.keycloak.OAuth2Constants) ClientModel(org.keycloak.models.ClientModel) RoleModel(org.keycloak.models.RoleModel) ClientScopeModel(org.keycloak.models.ClientScopeModel)

Example 19 with ClientScopeModel

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

the class AccountRestService method createConsent.

/**
 * Create a new consent model object from the requested consent object
 * for the given client model.
 *
 * @param client    client to create a consent for
 * @param requested list of client scopes that the new consent should contain
 * @return newly created consent model
 * @throws IllegalArgumentException throws an exception if the scope id is not available
 */
private UserConsentModel createConsent(ClientModel client, ConsentRepresentation requested) throws IllegalArgumentException {
    UserConsentModel consent = new UserConsentModel(client);
    Map<String, ClientScopeModel> availableGrants = realm.getClientScopesStream().collect(Collectors.toMap(ClientScopeModel::getId, Function.identity()));
    if (client.isConsentRequired()) {
        availableGrants.put(client.getId(), client);
    }
    for (ConsentScopeRepresentation scopeRepresentation : requested.getGrantedScopes()) {
        ClientScopeModel scopeModel = availableGrants.get(scopeRepresentation.getId());
        if (scopeModel == null) {
            String msg = String.format("Scope id %s does not exist for client %s.", scopeRepresentation, consent.getClient().getName());
            event.error(msg);
            throw new IllegalArgumentException(msg);
        } else {
            consent.addGrantedClientScope(scopeModel);
        }
    }
    return consent;
}
Also used : ConsentScopeRepresentation(org.keycloak.representations.account.ConsentScopeRepresentation) ClientScopeModel(org.keycloak.models.ClientScopeModel) UserConsentModel(org.keycloak.models.UserConsentModel)

Example 20 with ClientScopeModel

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

the class ClientResource method removeDefaultClientScope.

@DELETE
@NoCache
@Path("default-client-scopes/{clientScopeId}")
public void removeDefaultClientScope(@PathParam("clientScopeId") String clientScopeId) {
    auth.clients().requireManage(client);
    ClientScopeModel clientScope = realm.getClientScopeById(clientScopeId);
    if (clientScope == null) {
        throw new javax.ws.rs.NotFoundException("Client scope not found");
    }
    client.removeClientScope(clientScope);
    adminEvent.operation(OperationType.DELETE).resource(ResourceType.CLIENT_SCOPE_CLIENT_MAPPING).resourcePath(session.getContext().getUri()).success();
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) ClientScopeModel(org.keycloak.models.ClientScopeModel) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Aggregations

ClientScopeModel (org.keycloak.models.ClientScopeModel)58 ClientModel (org.keycloak.models.ClientModel)22 RealmModel (org.keycloak.models.RealmModel)18 KeycloakSession (org.keycloak.models.KeycloakSession)17 UserConsentModel (org.keycloak.models.UserConsentModel)14 HashMap (java.util.HashMap)11 Map (java.util.Map)9 UserModel (org.keycloak.models.UserModel)9 HashSet (java.util.HashSet)8 Test (org.junit.Test)8 RoleModel (org.keycloak.models.RoleModel)8 MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 NotFoundException (javax.ws.rs.NotFoundException)6 ArtifactBindingUtils.computeArtifactBindingIdentifierString (org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString)6 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)6 IOException (java.io.IOException)5 Path (javax.ws.rs.Path)5 NoCache (org.jboss.resteasy.annotations.cache.NoCache)5