Search in sources :

Example 1 with ClientScopeModel

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

the class ClientScopePolicyProviderFactory method onExport.

@Override
public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorizationProvider) {
    Map<String, String> config = new HashMap<>();
    Set<ClientScopePolicyRepresentation.ClientScopeDefinition> clientScopes = toRepresentation(policy, authorizationProvider).getClientScopes();
    for (ClientScopePolicyRepresentation.ClientScopeDefinition clientScopeDefinition : clientScopes) {
        ClientScopeModel clientScope = authorizationProvider.getRealm().getClientScopeById(clientScopeDefinition.getId());
        clientScopeDefinition.setId(clientScope.getName());
    }
    try {
        config.put("clientScopes", JsonSerialization.writeValueAsString(clientScopes));
    } catch (IOException e) {
        throw new RuntimeException("Failed to export client scope policy [" + policy.getName() + "]", e);
    }
    representation.setConfig(config);
}
Also used : ClientScopeDefinition(org.keycloak.representations.idm.authorization.ClientScopePolicyRepresentation.ClientScopeDefinition) HashMap(java.util.HashMap) ClientScopeDefinition(org.keycloak.representations.idm.authorization.ClientScopePolicyRepresentation.ClientScopeDefinition) ClientScopePolicyRepresentation(org.keycloak.representations.idm.authorization.ClientScopePolicyRepresentation) ClientScopeModel(org.keycloak.models.ClientScopeModel) IOException(java.io.IOException)

Example 2 with ClientScopeModel

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

the class CibaGrantType method createUserSession.

private UserSessionModel createUserSession(CIBAAuthenticationRequest request, Map<String, String> additionalParams) {
    RootAuthenticationSessionModel rootAuthSession = session.authenticationSessions().createRootAuthenticationSession(realm);
    // here Client Model of CD(Consumption Device) needs to be used to bind its Client Session with User Session.
    AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
    authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    authSession.setAction(AuthenticatedClientSessionModel.Action.AUTHENTICATE.name());
    authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
    authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, request.getScope());
    if (additionalParams != null) {
        for (String paramName : additionalParams.keySet()) {
            authSession.setClientNote(ADDITIONAL_CALLBACK_PARAMS_PREFIX + paramName, additionalParams.get(paramName));
        }
    }
    if (request.getOtherClaims() != null) {
        for (String paramName : request.getOtherClaims().keySet()) {
            authSession.setClientNote(ADDITIONAL_BACKCHANNEL_REQ_PARAMS_PREFIX + paramName, request.getOtherClaims().get(paramName).toString());
        }
    }
    UserModel user = session.users().getUserById(realm, request.getSubject());
    if (user == null) {
        event.error(Errors.USERNAME_MISSING);
        throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "Could not identify user", Response.Status.BAD_REQUEST);
    }
    if (!user.isEnabled()) {
        event.error(Errors.USER_DISABLED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User disabled", Response.Status.BAD_REQUEST);
    }
    logger.debugf("CIBA Grant :: user model found. user.getId() = %s, user.getEmail() = %s, user.getUsername() = %s.", user.getId(), user.getEmail(), user.getUsername());
    authSession.setAuthenticatedUser(user);
    if (user.getRequiredActionsStream().count() > 0) {
        event.error(Errors.RESOLVE_REQUIRED_ACTIONS);
        throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "Account is not fully set up", Response.Status.BAD_REQUEST);
    }
    AuthenticationManager.setClientScopesInSession(authSession);
    ClientSessionContext context = AuthenticationProcessor.attachSession(authSession, null, session, realm, session.getContext().getConnection(), event);
    UserSessionModel userSession = context.getClientSession().getUserSession();
    if (userSession == null) {
        event.error(Errors.USER_SESSION_NOT_FOUND);
        throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "User session is not found", Response.Status.BAD_REQUEST);
    }
    // authorization (consent)
    UserConsentModel grantedConsent = session.users().getConsentByClient(realm, user.getId(), client.getId());
    if (grantedConsent == null) {
        grantedConsent = new UserConsentModel(client);
        session.users().addConsent(realm, user.getId(), grantedConsent);
        if (logger.isTraceEnabled()) {
            grantedConsent.getGrantedClientScopes().forEach(i -> logger.tracef("CIBA Grant :: Consent granted. %s", i.getName()));
        }
    }
    boolean updateConsentRequired = false;
    for (String clientScopeId : authSession.getClientScopes()) {
        ClientScopeModel clientScope = KeycloakModelUtils.findClientScopeById(realm, client, clientScopeId);
        if (clientScope != null && !grantedConsent.isClientScopeGranted(clientScope) && clientScope.isDisplayOnConsentScreen()) {
            grantedConsent.addGrantedClientScope(clientScope);
            updateConsentRequired = true;
        }
    }
    if (updateConsentRequired) {
        session.users().updateConsent(realm, user.getId(), grantedConsent);
        if (logger.isTraceEnabled()) {
            grantedConsent.getGrantedClientScopes().forEach(i -> logger.tracef("CIBA Grant :: Consent updated. %s", i.getName()));
        }
    }
    event.detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED);
    event.detail(Details.CODE_ID, userSession.getId());
    event.session(userSession.getId());
    event.user(user);
    logger.debugf("Successfully verified Authe Req Id '%s'. User session: '%s', client: '%s'", request, userSession.getId(), client.getId());
    return userSession;
}
Also used : UserModel(org.keycloak.models.UserModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) ClientScopeModel(org.keycloak.models.ClientScopeModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) UserConsentModel(org.keycloak.models.UserConsentModel)

Example 3 with ClientScopeModel

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

the class MapUserProvider method updateConsent.

@Override
public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) {
    LOG.tracef("updateConsent(%s, %s, %s)%s", realm, userId, consent, getShortStackTrace());
    MapUserEntity user = getEntityByIdOrThrow(realm, userId);
    MapUserConsentEntity userConsentEntity = user.getUserConsent(consent.getClient().getId()).orElseThrow(() -> new ModelException("Consent not found for client [" + consent.getClient().getId() + "] and user [" + userId + "]"));
    userConsentEntity.setGrantedClientScopesIds(consent.getGrantedClientScopes().stream().map(ClientScopeModel::getId).collect(Collectors.toSet()));
    userConsentEntity.setLastUpdatedDate(Time.currentTimeMillis());
}
Also used : ModelException(org.keycloak.models.ModelException) ClientScopeModel(org.keycloak.models.ClientScopeModel)

Example 4 with ClientScopeModel

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

the class ApplicationsBean method toApplicationEntry.

/**
 * Constructs a {@link ApplicationEntry} from the specified parameters.
 *
 * @param session a reference to the {@code Keycloak} session.
 * @param realm a reference to the realm.
 * @param user a reference to the user.
 * @param client a reference to the client that contains the applications.
 * @param offlineClients a {@link Set} containing the offline clients.
 * @return the constructed {@link ApplicationEntry} instance or {@code null} if the user can't access the applications
 * in the specified client.
 */
private ApplicationEntry toApplicationEntry(final KeycloakSession session, final RealmModel realm, final UserModel user, final ClientModel client, final Set<ClientModel> offlineClients) {
    // Construct scope parameter with all optional scopes to see all potentially available roles
    Stream<ClientScopeModel> allClientScopes = Stream.concat(client.getClientScopes(true).values().stream(), client.getClientScopes(false).values().stream());
    allClientScopes = Stream.concat(allClientScopes, Stream.of(client)).distinct();
    Set<RoleModel> availableRoles = TokenManager.getAccess(user, client, allClientScopes);
    // unless this is can be changed by approving/revoking consent
    if (!isAdminClient(client) && availableRoles.isEmpty() && !client.isConsentRequired()) {
        return null;
    }
    List<RoleModel> realmRolesAvailable = new LinkedList<>();
    MultivaluedHashMap<String, ClientRoleEntry> resourceRolesAvailable = new MultivaluedHashMap<>();
    processRoles(availableRoles, realmRolesAvailable, resourceRolesAvailable);
    List<ClientScopeModel> orderedScopes = new LinkedList<>();
    if (client.isConsentRequired()) {
        UserConsentModel consent = session.users().getConsentByClient(realm, user.getId(), client.getId());
        if (consent != null) {
            orderedScopes.addAll(consent.getGrantedClientScopes());
        }
    }
    List<String> clientScopesGranted = orderedScopes.stream().sorted(OrderedModel.OrderedModelComparator.getInstance()).map(ClientScopeModel::getConsentScreenText).collect(Collectors.toList());
    List<String> additionalGrants = new ArrayList<>();
    if (offlineClients.contains(client)) {
        additionalGrants.add("${offlineToken}");
    }
    return new ApplicationEntry(session, realmRolesAvailable, resourceRolesAvailable, client, clientScopesGranted, additionalGrants);
}
Also used : ArrayList(java.util.ArrayList) ClientScopeModel(org.keycloak.models.ClientScopeModel) RoleModel(org.keycloak.models.RoleModel) LinkedList(java.util.LinkedList) UserConsentModel(org.keycloak.models.UserConsentModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap)

Example 5 with ClientScopeModel

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

the class JpaRealmProvider method addClientScopes.

@Override
public void addClientScopes(RealmModel realm, ClientModel client, Set<ClientScopeModel> clientScopes, boolean defaultScope) {
    // Defaults to openid-connect
    String clientProtocol = client.getProtocol() == null ? OIDCLoginProtocol.LOGIN_PROTOCOL : client.getProtocol();
    Map<String, ClientScopeModel> existingClientScopes = getClientScopes(realm, client, true);
    existingClientScopes.putAll(getClientScopes(realm, client, false));
    clientScopes.stream().filter(clientScope -> !existingClientScopes.containsKey(clientScope.getName())).filter(clientScope -> Objects.equals(clientScope.getProtocol(), clientProtocol)).forEach(clientScope -> {
        ClientScopeClientMappingEntity entity = new ClientScopeClientMappingEntity();
        entity.setClientScopeId(clientScope.getId());
        entity.setClientId(client.getId());
        entity.setDefaultScope(defaultScope);
        em.persist(entity);
        em.flush();
        em.detach(entity);
    });
}
Also used : GroupEntity(org.keycloak.models.jpa.entities.GroupEntity) Join(javax.persistence.criteria.Join) ClientProvider(org.keycloak.models.ClientProvider) RoleContainerModel(org.keycloak.models.RoleContainerModel) StackUtil.getShortStackTrace(org.keycloak.common.util.StackUtil.getShortStackTrace) Predicate(javax.persistence.criteria.Predicate) Map(java.util.Map) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) DeploymentStateProvider(org.keycloak.models.DeploymentStateProvider) ClientEntity(org.keycloak.models.jpa.entities.ClientEntity) Time(org.keycloak.common.util.Time) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) RoleProvider(org.keycloak.models.RoleProvider) StreamsUtil.closing(org.keycloak.utils.StreamsUtil.closing) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) Collectors(java.util.stream.Collectors) PaginationUtils.paginateQuery(org.keycloak.models.jpa.PaginationUtils.paginateQuery) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) RoleEntity(org.keycloak.models.jpa.entities.RoleEntity) ClientModel(org.keycloak.models.ClientModel) ClientScopeEntity(org.keycloak.models.jpa.entities.ClientScopeEntity) RealmLocalizationTextsEntity(org.keycloak.models.jpa.entities.RealmLocalizationTextsEntity) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) HashMap(java.util.HashMap) MigrationModel(org.keycloak.migration.MigrationModel) Function(java.util.function.Function) TypedQuery(javax.persistence.TypedQuery) ArrayList(java.util.ArrayList) RealmProvider(org.keycloak.models.RealmProvider) CriteriaDelete(javax.persistence.criteria.CriteriaDelete) GroupModel(org.keycloak.models.GroupModel) GroupProvider(org.keycloak.models.GroupProvider) ClientModelLazyDelegate(org.keycloak.models.delegate.ClientModelLazyDelegate) Root(javax.persistence.criteria.Root) RoleRemovedEvent(org.keycloak.models.RoleContainerModel.RoleRemovedEvent) KeycloakSession(org.keycloak.models.KeycloakSession) ClientScopeClientMappingEntity(org.keycloak.models.jpa.entities.ClientScopeClientMappingEntity) EntityManager(javax.persistence.EntityManager) JpaUtils(org.keycloak.connections.jpa.util.JpaUtils) ModelException(org.keycloak.models.ModelException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) LockModeType(javax.persistence.LockModeType) RealmEntity(org.keycloak.models.jpa.entities.RealmEntity) ClientScopeProvider(org.keycloak.models.ClientScopeProvider) ClientAttributeEntity(org.keycloak.models.jpa.entities.ClientAttributeEntity) ClientScopeClientMappingEntity(org.keycloak.models.jpa.entities.ClientScopeClientMappingEntity) ClientScopeModel(org.keycloak.models.ClientScopeModel)

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