Search in sources :

Example 1 with UserConsentModel

use of org.keycloak.models.UserConsentModel 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 2 with UserConsentModel

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

the class MapUserConsentEntity method toModel.

public static UserConsentModel toModel(RealmModel realm, MapUserConsentEntity entity) {
    if (entity == null) {
        return null;
    }
    ClientModel client = realm.getClientById(entity.getClientId());
    if (client == null) {
        throw new ModelException("Client with id " + entity.getClientId() + " is not available");
    }
    UserConsentModel model = new UserConsentModel(client);
    model.setCreatedDate(entity.getCreatedDate());
    model.setLastUpdatedDate(entity.getLastUpdatedDate());
    Set<String> grantedClientScopesIds = entity.getGrantedClientScopesIds();
    if (grantedClientScopesIds != null && !grantedClientScopesIds.isEmpty()) {
        grantedClientScopesIds.stream().map(scopeId -> KeycloakModelUtils.findClientScopeById(realm, client, scopeId)).filter(Objects::nonNull).forEach(model::addGrantedClientScope);
    }
    return model;
}
Also used : ClientModel(org.keycloak.models.ClientModel) ModelException(org.keycloak.models.ModelException) UserConsentModel(org.keycloak.models.UserConsentModel)

Example 3 with UserConsentModel

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

the class ApplicationsBean method getApplications.

private Stream<ClientModel> getApplications(KeycloakSession session, RealmModel realm, UserModel user) {
    Predicate<ClientModel> bearerOnly = ClientModel::isBearerOnly;
    Stream<ClientModel> clients = realm.getClientsStream().filter(bearerOnly.negate());
    Predicate<ClientModel> isLocal = client -> new StorageId(client.getId()).isLocal();
    return Stream.concat(clients, session.users().getConsentsStream(realm, user.getId()).map(UserConsentModel::getClient).filter(isLocal.negate())).distinct();
}
Also used : ClientModel(org.keycloak.models.ClientModel) AdminPermissions(org.keycloak.services.resources.admin.permissions.AdminPermissions) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) Predicate(java.util.function.Predicate) Constants(org.keycloak.models.Constants) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) TokenManager(org.keycloak.protocol.oidc.TokenManager) Collectors(java.util.stream.Collectors) StorageId(org.keycloak.storage.StorageId) ResolveRelative(org.keycloak.services.util.ResolveRelative) ArrayList(java.util.ArrayList) OrderedModel(org.keycloak.models.OrderedModel) Objects(java.util.Objects) List(java.util.List) UserModel(org.keycloak.models.UserModel) Stream(java.util.stream.Stream) UserSessionManager(org.keycloak.services.managers.UserSessionManager) UserConsentModel(org.keycloak.models.UserConsentModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) LinkedList(java.util.LinkedList) ClientModel(org.keycloak.models.ClientModel) StorageId(org.keycloak.storage.StorageId)

Example 4 with UserConsentModel

use of org.keycloak.models.UserConsentModel 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 UserConsentModel

use of org.keycloak.models.UserConsentModel 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)

Aggregations

UserConsentModel (org.keycloak.models.UserConsentModel)32 ClientModel (org.keycloak.models.ClientModel)26 UserModel (org.keycloak.models.UserModel)20 RealmModel (org.keycloak.models.RealmModel)17 ClientScopeModel (org.keycloak.models.ClientScopeModel)16 KeycloakSession (org.keycloak.models.KeycloakSession)15 Test (org.junit.Test)10 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)10 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)10 ArrayList (java.util.ArrayList)5 LinkedList (java.util.LinkedList)5 List (java.util.List)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)4 ModelException (org.keycloak.models.ModelException)4 StorageId (org.keycloak.storage.StorageId)4 Objects (java.util.Objects)3 Set (java.util.Set)3 Collectors (java.util.stream.Collectors)3