Search in sources :

Example 6 with ClientScopeModel

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

the class JpaUserProvider method toConsentModel.

private UserConsentModel toConsentModel(RealmModel realm, UserConsentEntity entity) {
    if (entity == null) {
        return null;
    }
    StorageId clientStorageId = null;
    if (entity.getClientId() == null) {
        clientStorageId = new StorageId(entity.getClientStorageProvider(), entity.getExternalClientId());
    } else {
        clientStorageId = new StorageId(entity.getClientId());
    }
    ClientModel client = realm.getClientById(clientStorageId.getId());
    if (client == null) {
        throw new ModelException("Client with id " + clientStorageId.getId() + " is not available");
    }
    UserConsentModel model = new UserConsentModel(client);
    model.setCreatedDate(entity.getCreatedDate());
    model.setLastUpdatedDate(entity.getLastUpdatedDate());
    Collection<UserConsentClientScopeEntity> grantedClientScopeEntities = entity.getGrantedClientScopes();
    if (grantedClientScopeEntities != null) {
        for (UserConsentClientScopeEntity grantedClientScope : grantedClientScopeEntities) {
            ClientScopeModel grantedClientScopeModel = KeycloakModelUtils.findClientScopeById(realm, client, grantedClientScope.getScopeId());
            if (grantedClientScopeModel != null) {
                model.addGrantedClientScope(grantedClientScopeModel);
            }
        }
    }
    return model;
}
Also used : ClientModel(org.keycloak.models.ClientModel) ModelException(org.keycloak.models.ModelException) ClientScopeModel(org.keycloak.models.ClientScopeModel) StorageId(org.keycloak.storage.StorageId) UserConsentClientScopeEntity(org.keycloak.models.jpa.entities.UserConsentClientScopeEntity) UserConsentModel(org.keycloak.models.UserConsentModel)

Example 7 with ClientScopeModel

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

the class TestingResourceProvider method generateAudienceClientScope.

/**
 * Generate new client scope for specified service client. The "Frontend" clients, who will use this client scope, will be able to
 * send their access token to authenticate against specified service client
 *
 * @param clientId Client ID of service client (typically bearer-only client)
 * @return ID of the newly generated clientScope
 */
@Path("generate-audience-client-scope")
@POST
@NoCache
public String generateAudienceClientScope(@QueryParam("realm") final String realmName, @QueryParam("clientId") final String clientId) {
    try {
        RealmModel realm = getRealmByName(realmName);
        ClientModel serviceClient = realm.getClientByClientId(clientId);
        if (serviceClient == null) {
            throw new NotFoundException("Referenced service client doesn't exist");
        }
        ClientScopeModel clientScopeModel = realm.addClientScope(clientId);
        clientScopeModel.setProtocol(serviceClient.getProtocol() == null ? OIDCLoginProtocol.LOGIN_PROTOCOL : serviceClient.getProtocol());
        clientScopeModel.setDisplayOnConsentScreen(true);
        clientScopeModel.setConsentScreenText(clientId);
        clientScopeModel.setIncludeInTokenScope(true);
        // Add audience protocol mapper
        ProtocolMapperModel audienceMapper = AudienceProtocolMapper.createClaimMapper("Audience for " + clientId, clientId, null, true, false);
        clientScopeModel.addProtocolMapper(audienceMapper);
        return clientScopeModel.getId();
    } catch (ModelDuplicateException e) {
        throw new BadRequestException("Client Scope " + clientId + " already exists");
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) NotFoundException(javax.ws.rs.NotFoundException) BadRequestException(javax.ws.rs.BadRequestException) ClientScopeModel(org.keycloak.models.ClientScopeModel) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 8 with ClientScopeModel

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

the class RepresentationToModel method toModel.

public static UserConsentModel toModel(RealmModel newRealm, UserConsentRepresentation consentRep) {
    ClientModel client = newRealm.getClientByClientId(consentRep.getClientId());
    if (client == null) {
        throw new RuntimeException("Unable to find client consent mappings for client: " + consentRep.getClientId());
    }
    UserConsentModel consentModel = new UserConsentModel(client);
    consentModel.setCreatedDate(consentRep.getCreatedDate());
    consentModel.setLastUpdatedDate(consentRep.getLastUpdatedDate());
    if (consentRep.getGrantedClientScopes() != null) {
        for (String scopeName : consentRep.getGrantedClientScopes()) {
            ClientScopeModel clientScope = KeycloakModelUtils.getClientScopeByName(newRealm, scopeName);
            if (clientScope == null) {
                throw new RuntimeException("Unable to find client scope referenced in consent mappings of user. Client scope name: " + scopeName);
            }
            consentModel.addGrantedClientScope(clientScope);
        }
    }
    // Backwards compatibility. If user had consent for "offline_access" role, we treat it as he has consent for "offline_access" client scope
    if (consentRep.getGrantedRealmRoles() != null) {
        if (consentRep.getGrantedRealmRoles().contains(OAuth2Constants.OFFLINE_ACCESS)) {
            ClientScopeModel offlineScope = client.getClientScopes(false).get(OAuth2Constants.OFFLINE_ACCESS);
            if (offlineScope == null) {
                logger.warn("Unable to find offline_access scope referenced in grantedRoles of user");
            }
            consentModel.addGrantedClientScope(offlineScope);
        }
    }
    return consentModel;
}
Also used : ClientModel(org.keycloak.models.ClientModel) ClientScopeModel(org.keycloak.models.ClientScopeModel) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) UserConsentModel(org.keycloak.models.UserConsentModel)

Example 9 with ClientScopeModel

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

the class RepresentationToModel method createClient.

private static ClientModel createClient(KeycloakSession session, RealmModel realm, ClientRepresentation resourceRep, Map<String, String> mappedFlows) {
    logger.debugv("Create client: {0}", resourceRep.getClientId());
    ClientModel client = resourceRep.getId() != null ? realm.addClient(resourceRep.getId(), resourceRep.getClientId()) : realm.addClient(resourceRep.getClientId());
    if (resourceRep.getName() != null)
        client.setName(resourceRep.getName());
    if (resourceRep.getDescription() != null)
        client.setDescription(resourceRep.getDescription());
    if (resourceRep.isEnabled() != null)
        client.setEnabled(resourceRep.isEnabled());
    if (resourceRep.isAlwaysDisplayInConsole() != null)
        client.setAlwaysDisplayInConsole(resourceRep.isAlwaysDisplayInConsole());
    client.setManagementUrl(resourceRep.getAdminUrl());
    if (resourceRep.isSurrogateAuthRequired() != null)
        client.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired());
    if (resourceRep.getRootUrl() != null)
        client.setRootUrl(resourceRep.getRootUrl());
    if (resourceRep.getBaseUrl() != null)
        client.setBaseUrl(resourceRep.getBaseUrl());
    if (resourceRep.isBearerOnly() != null)
        client.setBearerOnly(resourceRep.isBearerOnly());
    if (resourceRep.isConsentRequired() != null)
        client.setConsentRequired(resourceRep.isConsentRequired());
    // Backwards compatibility only
    if (resourceRep.isDirectGrantsOnly() != null) {
        logger.warn("Using deprecated 'directGrantsOnly' configuration in JSON representation. It will be removed in future versions");
        client.setStandardFlowEnabled(!resourceRep.isDirectGrantsOnly());
        client.setDirectAccessGrantsEnabled(resourceRep.isDirectGrantsOnly());
    }
    if (resourceRep.isStandardFlowEnabled() != null)
        client.setStandardFlowEnabled(resourceRep.isStandardFlowEnabled());
    if (resourceRep.isImplicitFlowEnabled() != null)
        client.setImplicitFlowEnabled(resourceRep.isImplicitFlowEnabled());
    if (resourceRep.isDirectAccessGrantsEnabled() != null)
        client.setDirectAccessGrantsEnabled(resourceRep.isDirectAccessGrantsEnabled());
    if (resourceRep.isServiceAccountsEnabled() != null)
        client.setServiceAccountsEnabled(resourceRep.isServiceAccountsEnabled());
    if (resourceRep.isPublicClient() != null)
        client.setPublicClient(resourceRep.isPublicClient());
    if (resourceRep.isFrontchannelLogout() != null)
        client.setFrontchannelLogout(resourceRep.isFrontchannelLogout());
    // set defaults to openid-connect if no protocol specified
    if (resourceRep.getProtocol() != null) {
        client.setProtocol(resourceRep.getProtocol());
    } else {
        client.setProtocol(OIDC);
    }
    if (resourceRep.getNodeReRegistrationTimeout() != null) {
        client.setNodeReRegistrationTimeout(resourceRep.getNodeReRegistrationTimeout());
    } else {
        client.setNodeReRegistrationTimeout(-1);
    }
    if (resourceRep.getNotBefore() != null) {
        client.setNotBefore(resourceRep.getNotBefore());
    }
    if (resourceRep.getClientAuthenticatorType() != null) {
        client.setClientAuthenticatorType(resourceRep.getClientAuthenticatorType());
    } else {
        client.setClientAuthenticatorType(KeycloakModelUtils.getDefaultClientAuthenticatorType());
    }
    client.setSecret(resourceRep.getSecret());
    if (resourceRep.getAttributes() != null) {
        for (Map.Entry<String, String> entry : resourceRep.getAttributes().entrySet()) {
            client.setAttribute(entry.getKey(), entry.getValue());
        }
    }
    if ("saml".equals(resourceRep.getProtocol()) && (resourceRep.getAttributes() == null || !resourceRep.getAttributes().containsKey("saml.artifact.binding.identifier"))) {
        client.setAttribute("saml.artifact.binding.identifier", computeArtifactBindingIdentifierString(resourceRep.getClientId()));
    }
    if (resourceRep.getAuthenticationFlowBindingOverrides() != null) {
        for (Map.Entry<String, String> entry : resourceRep.getAuthenticationFlowBindingOverrides().entrySet()) {
            if (entry.getValue() == null || entry.getValue().trim().equals("")) {
                continue;
            } else {
                String flowId = entry.getValue();
                // check if flow id was mapped when the flows were imported
                if (mappedFlows != null && mappedFlows.containsKey(flowId)) {
                    flowId = mappedFlows.get(flowId);
                }
                if (client.getRealm().getAuthenticationFlowById(flowId) == null) {
                    throw new RuntimeException("Unable to resolve auth flow binding override for: " + entry.getKey());
                }
                client.setAuthenticationFlowBindingOverride(entry.getKey(), flowId);
            }
        }
    }
    if (resourceRep.getRedirectUris() != null) {
        for (String redirectUri : resourceRep.getRedirectUris()) {
            client.addRedirectUri(redirectUri);
        }
    }
    if (resourceRep.getWebOrigins() != null) {
        for (String webOrigin : resourceRep.getWebOrigins()) {
            logger.debugv("Client: {0} webOrigin: {1}", resourceRep.getClientId(), webOrigin);
            client.addWebOrigin(webOrigin);
        }
    } else {
        // add origins from redirect uris
        if (resourceRep.getRedirectUris() != null) {
            Set<String> origins = new HashSet<String>();
            for (String redirectUri : resourceRep.getRedirectUris()) {
                logger.debugv("add redirect-uri to origin: {0}", redirectUri);
                if (redirectUri.startsWith("http")) {
                    String origin = UriUtils.getOrigin(redirectUri);
                    logger.debugv("adding default client origin: {0}", origin);
                    origins.add(origin);
                }
            }
            if (origins.size() > 0) {
                client.setWebOrigins(origins);
            }
        }
    }
    if (resourceRep.getRegisteredNodes() != null) {
        for (Map.Entry<String, Integer> entry : resourceRep.getRegisteredNodes().entrySet()) {
            client.registerNode(entry.getKey(), entry.getValue());
        }
    }
    if (resourceRep.getProtocolMappers() != null) {
        // first, remove all default/built in mappers
        client.getProtocolMappersStream().collect(Collectors.toList()).forEach(client::removeProtocolMapper);
        for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) {
            client.addProtocolMapper(toModel(mapper));
        }
        MigrationUtils.updateProtocolMappers(client);
    }
    if (resourceRep.getClientTemplate() != null) {
        String clientTemplateName = KeycloakModelUtils.convertClientScopeName(resourceRep.getClientTemplate());
        addClientScopeToClient(realm, client, clientTemplateName, true);
    }
    if (resourceRep.getDefaultClientScopes() != null || resourceRep.getOptionalClientScopes() != null) {
        // First remove all default/built in client scopes
        for (ClientScopeModel clientScope : client.getClientScopes(true).values()) {
            client.removeClientScope(clientScope);
        }
        // First remove all default/built in client scopes
        for (ClientScopeModel clientScope : client.getClientScopes(false).values()) {
            client.removeClientScope(clientScope);
        }
    }
    if (resourceRep.getDefaultClientScopes() != null) {
        for (String clientScopeName : resourceRep.getDefaultClientScopes()) {
            addClientScopeToClient(realm, client, clientScopeName, true);
        }
    }
    if (resourceRep.getOptionalClientScopes() != null) {
        for (String clientScopeName : resourceRep.getOptionalClientScopes()) {
            addClientScopeToClient(realm, client, clientScopeName, false);
        }
    }
    if (resourceRep.isFullScopeAllowed() != null) {
        client.setFullScopeAllowed(resourceRep.isFullScopeAllowed());
    } else {
        client.setFullScopeAllowed(!client.isConsentRequired());
    }
    client.updateClient();
    resourceRep.setId(client.getId());
    return client;
}
Also used : ClientModel(org.keycloak.models.ClientModel) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) ClientScopeModel(org.keycloak.models.ClientScopeModel) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) Map(java.util.Map) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 10 with ClientScopeModel

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

the class OIDCLoginProtocolFactory method createDefaultClientScopesImpl.

@Override
protected void createDefaultClientScopesImpl(RealmModel newRealm) {
    // name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, website, gender, birthdate, zoneinfo, locale, and updated_at.
    ClientScopeModel profileScope = newRealm.addClientScope(OAuth2Constants.SCOPE_PROFILE);
    profileScope.setDescription("OpenID Connect built-in scope: profile");
    profileScope.setDisplayOnConsentScreen(true);
    profileScope.setConsentScreenText(PROFILE_SCOPE_CONSENT_TEXT);
    profileScope.setIncludeInTokenScope(true);
    profileScope.setProtocol(getId());
    profileScope.addProtocolMapper(builtins.get(FULL_NAME));
    profileScope.addProtocolMapper(builtins.get(FAMILY_NAME));
    profileScope.addProtocolMapper(builtins.get(GIVEN_NAME));
    profileScope.addProtocolMapper(builtins.get(MIDDLE_NAME));
    profileScope.addProtocolMapper(builtins.get(NICKNAME));
    profileScope.addProtocolMapper(builtins.get(USERNAME));
    profileScope.addProtocolMapper(builtins.get(PROFILE_CLAIM));
    profileScope.addProtocolMapper(builtins.get(PICTURE));
    profileScope.addProtocolMapper(builtins.get(WEBSITE));
    profileScope.addProtocolMapper(builtins.get(GENDER));
    profileScope.addProtocolMapper(builtins.get(BIRTHDATE));
    profileScope.addProtocolMapper(builtins.get(ZONEINFO));
    profileScope.addProtocolMapper(builtins.get(LOCALE));
    profileScope.addProtocolMapper(builtins.get(UPDATED_AT));
    ClientScopeModel emailScope = newRealm.addClientScope(OAuth2Constants.SCOPE_EMAIL);
    emailScope.setDescription("OpenID Connect built-in scope: email");
    emailScope.setDisplayOnConsentScreen(true);
    emailScope.setConsentScreenText(EMAIL_SCOPE_CONSENT_TEXT);
    emailScope.setIncludeInTokenScope(true);
    emailScope.setProtocol(getId());
    emailScope.addProtocolMapper(builtins.get(EMAIL));
    emailScope.addProtocolMapper(builtins.get(EMAIL_VERIFIED));
    ClientScopeModel addressScope = newRealm.addClientScope(OAuth2Constants.SCOPE_ADDRESS);
    addressScope.setDescription("OpenID Connect built-in scope: address");
    addressScope.setDisplayOnConsentScreen(true);
    addressScope.setConsentScreenText(ADDRESS_SCOPE_CONSENT_TEXT);
    addressScope.setIncludeInTokenScope(true);
    addressScope.setProtocol(getId());
    addressScope.addProtocolMapper(builtins.get(ADDRESS));
    ClientScopeModel phoneScope = newRealm.addClientScope(OAuth2Constants.SCOPE_PHONE);
    phoneScope.setDescription("OpenID Connect built-in scope: phone");
    phoneScope.setDisplayOnConsentScreen(true);
    phoneScope.setConsentScreenText(PHONE_SCOPE_CONSENT_TEXT);
    phoneScope.setIncludeInTokenScope(true);
    phoneScope.setProtocol(getId());
    phoneScope.addProtocolMapper(builtins.get(PHONE_NUMBER));
    phoneScope.addProtocolMapper(builtins.get(PHONE_NUMBER_VERIFIED));
    // 'profile' and 'email' will be default scopes for now. 'address' and 'phone' will be optional scopes
    newRealm.addDefaultClientScope(profileScope, true);
    newRealm.addDefaultClientScope(emailScope, true);
    newRealm.addDefaultClientScope(addressScope, false);
    newRealm.addDefaultClientScope(phoneScope, false);
    RoleModel offlineRole = newRealm.getRole(OAuth2Constants.OFFLINE_ACCESS);
    if (offlineRole != null) {
        ClientScopeModel offlineAccessScope = KeycloakModelUtils.getClientScopeByName(newRealm, OAuth2Constants.OFFLINE_ACCESS);
        if (offlineAccessScope == null) {
            DefaultClientScopes.createOfflineAccessClientScope(newRealm, offlineRole);
        }
    }
    addRolesClientScope(newRealm);
    addWebOriginsClientScope(newRealm);
    addMicroprofileJWTClientScope(newRealm);
}
Also used : ClientScopeModel(org.keycloak.models.ClientScopeModel) RoleModel(org.keycloak.models.RoleModel)

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