Search in sources :

Example 61 with ClientModel

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

the class RepresentationToModel method importRoles.

public static void importRoles(RolesRepresentation realmRoles, RealmModel realm) {
    if (realmRoles == null)
        return;
    if (realmRoles.getRealm() != null) {
        // realm roles
        for (RoleRepresentation roleRep : realmRoles.getRealm()) {
            if (!realm.getDefaultRole().getName().equals(roleRep.getName())) {
                // default role was already imported
                createRole(realm, roleRep);
            }
        }
    }
    if (realmRoles.getClient() != null) {
        for (Map.Entry<String, List<RoleRepresentation>> entry : realmRoles.getClient().entrySet()) {
            ClientModel client = realm.getClientByClientId(entry.getKey());
            if (client == null) {
                throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey());
            }
            for (RoleRepresentation roleRep : entry.getValue()) {
                // Application role may already exists (for example if it is defaultRole)
                RoleModel role = roleRep.getId() != null ? client.addRole(roleRep.getId(), roleRep.getName()) : client.addRole(roleRep.getName());
                role.setDescription(roleRep.getDescription());
                if (roleRep.getAttributes() != null) {
                    roleRep.getAttributes().forEach((key, value) -> role.setAttribute(key, value));
                }
            }
        }
    }
    // now that all roles are created, re-iterate and set up composites
    if (realmRoles.getRealm() != null) {
        // realm roles
        for (RoleRepresentation roleRep : realmRoles.getRealm()) {
            RoleModel role = realm.getRole(roleRep.getName());
            addComposites(role, roleRep, realm);
        }
    }
    if (realmRoles.getClient() != null) {
        for (Map.Entry<String, List<RoleRepresentation>> entry : realmRoles.getClient().entrySet()) {
            ClientModel client = realm.getClientByClientId(entry.getKey());
            if (client == null) {
                throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey());
            }
            for (RoleRepresentation roleRep : entry.getValue()) {
                RoleModel role = client.getRole(roleRep.getName());
                addComposites(role, roleRep, realm);
            }
        }
    }
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ClientModel(org.keycloak.models.ClientModel) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) RoleModel(org.keycloak.models.RoleModel) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) Map(java.util.Map) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap)

Example 62 with ClientModel

use of org.keycloak.models.ClientModel 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 63 with ClientModel

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

the class RepresentationToModel method importRealmAuthorizationSettings.

public static void importRealmAuthorizationSettings(RealmRepresentation rep, RealmModel newRealm, KeycloakSession session) {
    if (rep.getClients() != null) {
        rep.getClients().forEach(clientRepresentation -> {
            ClientModel client = newRealm.getClientByClientId(clientRepresentation.getClientId());
            importAuthorizationSettings(clientRepresentation, client, session);
        });
    }
}
Also used : ClientModel(org.keycloak.models.ClientModel)

Example 64 with ClientModel

use of org.keycloak.models.ClientModel 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 65 with ClientModel

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

the class KeycloakModelUtils method createClient.

private static ClientModel createClient(RealmModel realm, String name) {
    ClientModel client = realm.addClient(name);
    client.setClientAuthenticatorType(getDefaultClientAuthenticatorType());
    return client;
}
Also used : ClientModel(org.keycloak.models.ClientModel)

Aggregations

ClientModel (org.keycloak.models.ClientModel)344 RealmModel (org.keycloak.models.RealmModel)148 UserModel (org.keycloak.models.UserModel)88 RoleModel (org.keycloak.models.RoleModel)74 KeycloakSession (org.keycloak.models.KeycloakSession)67 Test (org.junit.Test)64 UserSessionModel (org.keycloak.models.UserSessionModel)41 ResourceServer (org.keycloak.authorization.model.ResourceServer)39 Policy (org.keycloak.authorization.model.Policy)38 HashMap (java.util.HashMap)37 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)36 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)34 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)34 List (java.util.List)32 Map (java.util.Map)32 Path (javax.ws.rs.Path)29 LinkedList (java.util.LinkedList)28 ClientScopeModel (org.keycloak.models.ClientScopeModel)28 ArrayList (java.util.ArrayList)27 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)27