Search in sources :

Example 26 with UserConsentModel

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

the class AuthenticationManager method actionRequired.

public static Response actionRequired(final KeycloakSession session, final AuthenticationSessionModel authSession, final HttpRequest request, final EventBuilder event) {
    final RealmModel realm = authSession.getRealm();
    final UserModel user = authSession.getAuthenticatedUser();
    final ClientModel client = authSession.getClient();
    evaluateRequiredActionTriggers(session, authSession, request, event, realm, user);
    logger.debugv("processAccessCode: go to oauth page?: {0}", client.isConsentRequired());
    event.detail(Details.CODE_ID, authSession.getParentSession().getId());
    Stream<String> requiredActions = user.getRequiredActionsStream();
    Response action = executionActions(session, authSession, request, event, realm, user, requiredActions);
    if (action != null)
        return action;
    // executionActions() method should remove any duplicate actions that might be in the clientSession
    action = executionActions(session, authSession, request, event, realm, user, authSession.getRequiredActions().stream());
    if (action != null)
        return action;
    // so the consent is required when running a verification flow of OAuth 2.0 Device Authorization Grant.
    if (client.isConsentRequired() || isOAuth2DeviceVerificationFlow(authSession)) {
        UserConsentModel grantedConsent = getEffectiveGrantedConsent(session, authSession);
        List<AuthorizationDetails> clientScopesToApprove = getClientScopesToApproveOnConsentScreen(grantedConsent, session);
        // Skip grant screen if everything was already approved by this user
        if (clientScopesToApprove.size() > 0) {
            String execution = AuthenticatedClientSessionModel.Action.OAUTH_GRANT.name();
            ClientSessionCode<AuthenticationSessionModel> accessCode = new ClientSessionCode<>(session, realm, authSession);
            accessCode.setAction(AuthenticatedClientSessionModel.Action.REQUIRED_ACTIONS.name());
            authSession.setAuthNote(AuthenticationProcessor.CURRENT_AUTHENTICATION_EXECUTION, execution);
            return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setExecution(execution).setClientSessionCode(accessCode.getOrGenerateCode()).setAccessRequest(clientScopesToApprove).createOAuthGrant();
        } else {
            String consentDetail = (grantedConsent != null) ? Details.CONSENT_VALUE_PERSISTED_CONSENT : Details.CONSENT_VALUE_NO_CONSENT_REQUIRED;
            event.detail(Details.CONSENT, consentDetail);
        }
    } else {
        event.detail(Details.CONSENT, Details.CONSENT_VALUE_NO_CONSENT_REQUIRED);
    }
    return null;
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserConsentModel(org.keycloak.models.UserConsentModel) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) ClientModel(org.keycloak.models.ClientModel) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) AuthorizationDetails(org.keycloak.rar.AuthorizationDetails)

Example 27 with UserConsentModel

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

the class AuthenticationManager method nextRequiredAction.

// Return null if action is not required. Or the name of the requiredAction in case it is required.
public static String nextRequiredAction(final KeycloakSession session, final AuthenticationSessionModel authSession, final HttpRequest request, final EventBuilder event) {
    final RealmModel realm = authSession.getRealm();
    final UserModel user = authSession.getAuthenticatedUser();
    final ClientModel client = authSession.getClient();
    evaluateRequiredActionTriggers(session, authSession, request, event, realm, user);
    Optional<String> reqAction = user.getRequiredActionsStream().findFirst();
    if (reqAction.isPresent()) {
        return reqAction.get();
    }
    if (!authSession.getRequiredActions().isEmpty()) {
        return authSession.getRequiredActions().iterator().next();
    }
    String kcAction = authSession.getClientNote(Constants.KC_ACTION);
    if (kcAction != null) {
        return kcAction;
    }
    if (client.isConsentRequired() || isOAuth2DeviceVerificationFlow(authSession)) {
        UserConsentModel grantedConsent = getEffectiveGrantedConsent(session, authSession);
        // See if any clientScopes need to be approved on consent screen
        List<AuthorizationDetails> clientScopesToApprove = getClientScopesToApproveOnConsentScreen(grantedConsent, session);
        if (!clientScopesToApprove.isEmpty()) {
            return CommonClientSessionModel.Action.OAUTH_GRANT.name();
        }
        String consentDetail = (grantedConsent != null) ? Details.CONSENT_VALUE_PERSISTED_CONSENT : Details.CONSENT_VALUE_NO_CONSENT_REQUIRED;
        event.detail(Details.CONSENT, consentDetail);
    } else {
        event.detail(Details.CONSENT, Details.CONSENT_VALUE_NO_CONSENT_REQUIRED);
    }
    return null;
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) AuthorizationDetails(org.keycloak.rar.AuthorizationDetails) UserConsentModel(org.keycloak.models.UserConsentModel)

Example 28 with UserConsentModel

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

the class UserResource method getConsents.

/**
 * Get consents granted by the user
 *
 * @return
 */
@Path("consents")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Stream<Map<String, Object>> getConsents() {
    auth.users().requireView(user);
    Set<ClientModel> offlineClients = new UserSessionManager(session).findClientsWithOfflineToken(realm, user);
    Set<ClientModel> clientsWithUserConsents = new HashSet<>();
    List<UserConsentModel> userConsents = session.users().getConsentsStream(realm, user.getId()).peek(ucm -> clientsWithUserConsents.add(ucm.getClient())).collect(Collectors.toList());
    return Stream.concat(userConsents.stream().map(consent -> toConsent(consent, offlineClients)), offlineClients.stream().filter(c -> !clientsWithUserConsents.contains(c)).map(this::toConsent));
}
Also used : UserSessionManager(org.keycloak.services.managers.UserSessionManager) EmailTemplateProvider(org.keycloak.email.EmailTemplateProvider) RedirectUtils(org.keycloak.protocol.oidc.utils.RedirectUtils) Produces(javax.ws.rs.Produces) USER_API(org.keycloak.userprofile.UserProfileContext.USER_API) MediaType(javax.ws.rs.core.MediaType) ErrorResponseException(org.keycloak.services.ErrorResponseException) Validation(org.keycloak.services.validation.Validation) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) UserConsentRepresentation(org.keycloak.representations.idm.UserConsentRepresentation) UriBuilder(javax.ws.rs.core.UriBuilder) Time(org.keycloak.common.util.Time) UserCredentialModel(org.keycloak.models.UserCredentialModel) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Set(java.util.Set) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) Stream(java.util.stream.Stream) LoginActionsService(org.keycloak.services.resources.LoginActionsService) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) WebApplicationException(javax.ws.rs.WebApplicationException) GET(javax.ws.rs.GET) Constants(org.keycloak.models.Constants) ArrayList(java.util.ArrayList) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) UserModel(org.keycloak.models.UserModel) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) UserConsentManager(org.keycloak.services.managers.UserConsentManager) ProviderFactory(org.keycloak.provider.ProviderFactory) UserManager(org.keycloak.models.UserManager) Properties(java.util.Properties) CredentialModel(org.keycloak.credential.CredentialModel) ExecuteActionsActionToken(org.keycloak.authentication.actiontoken.execactions.ExecuteActionsActionToken) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) EventType(org.keycloak.events.EventType) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) IMPERSONATOR_USERNAME(org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_USERNAME) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ValidationException(org.keycloak.userprofile.ValidationException) ResourceType(org.keycloak.events.admin.ResourceType) Path(javax.ws.rs.Path) GroupRepresentation(org.keycloak.representations.idm.GroupRepresentation) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) QueryParam(javax.ws.rs.QueryParam) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) Consumes(javax.ws.rs.Consumes) ReadOnlyException(org.keycloak.storage.ReadOnlyException) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) DefaultValue(javax.ws.rs.DefaultValue) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) BadRequestException(javax.ws.rs.BadRequestException) URI(java.net.URI) AccountFormService(org.keycloak.services.resources.account.AccountFormService) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) IMPERSONATOR_ID(org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_ID) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ForbiddenException(org.keycloak.services.ForbiddenException) ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) UserProfile(org.keycloak.userprofile.UserProfile) PathParam(javax.ws.rs.PathParam) UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) Profile(org.keycloak.common.Profile) Logger(org.jboss.logging.Logger) HashMap(java.util.HashMap) ServicesLogger(org.keycloak.services.ServicesLogger) ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) MessageFormat(java.text.MessageFormat) HashSet(java.util.HashSet) EventBuilder(org.keycloak.events.EventBuilder) UserConsentModel(org.keycloak.models.UserConsentModel) EmailException(org.keycloak.email.EmailException) GroupModel(org.keycloak.models.GroupModel) LinkedList(java.util.LinkedList) ProfileHelper(org.keycloak.utils.ProfileHelper) Status(javax.ws.rs.core.Response.Status) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) POST(javax.ws.rs.POST) UserLoginFailureModel(org.keycloak.models.UserLoginFailureModel) UserSessionModel(org.keycloak.models.UserSessionModel) TimeUnit(java.util.concurrent.TimeUnit) NoCache(org.jboss.resteasy.annotations.cache.NoCache) UserSessionManager(org.keycloak.services.managers.UserSessionManager) ModelException(org.keycloak.models.ModelException) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) ErrorResponse(org.keycloak.services.ErrorResponse) ClientModel(org.keycloak.models.ClientModel) UserConsentModel(org.keycloak.models.UserConsentModel) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 29 with UserConsentModel

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

the class UserConsentWithUserStorageModelTest method updateWithClientScopeRemovalTest.

@Test
@ModelTest
public void updateWithClientScopeRemovalTest(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionScopeRemoval1) -> {
        KeycloakSession currentSession = sessionScopeRemoval1;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        ClientModel fooClient = realm.getClientByClientId("foo-client");
        UserModel john = currentSession.users().getUserByUsername(realm, "john");
        UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId());
        Assert.assertEquals(1, johnConsent.getGrantedClientScopes().size());
        // Remove foo protocol mapper from johnConsent
        ClientScopeModel fooScope = KeycloakModelUtils.getClientScopeByName(realm, "foo");
        johnConsent.getGrantedClientScopes().remove(fooScope);
        currentSession.users().updateConsent(realm, john.getId(), johnConsent);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionScopeRemoval2) -> {
        KeycloakSession currentSession = sessionScopeRemoval2;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        ClientModel fooClient = realm.getClientByClientId("foo-client");
        UserModel john = currentSession.users().getUserByUsername(realm, "john");
        UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId());
        Assert.assertEquals(johnConsent.getGrantedClientScopes().size(), 0);
        Assert.assertTrue("Created date should be less than last updated date", johnConsent.getCreatedDate() < johnConsent.getLastUpdatedDate());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) ClientScopeModel(org.keycloak.models.ClientScopeModel) UserConsentModel(org.keycloak.models.UserConsentModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 30 with UserConsentModel

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

the class UserConsentWithUserStorageModelTest method getAllConsentTest.

@Test
@ModelTest
public void getAllConsentTest(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSessionACT) -> {
        KeycloakSession currentSession = currentSessionACT;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        ClientModel fooClient = realm.getClientByClientId("foo-client");
        UserModel john = currentSessionACT.users().getUserByUsername(realm, "john");
        UserModel mary = currentSessionACT.users().getUserByUsername(realm, "mary");
        Assert.assertEquals(2, currentSession.users().getConsentsStream(realm, john.getId()).count());
        ClientModel hardcodedClient = currentSessionACT.clients().getClientByClientId(realm, "hardcoded-client");
        List<UserConsentModel> maryConsents = currentSession.users().getConsentsStream(realm, mary.getId()).collect(Collectors.toList());
        Assert.assertEquals(2, maryConsents.size());
        UserConsentModel maryConsent = maryConsents.get(0);
        UserConsentModel maryHardcodedConsent = maryConsents.get(1);
        if (maryConsents.get(0).getClient().getId().equals(hardcodedClient.getId())) {
            maryConsent = maryConsents.get(1);
            maryHardcodedConsent = maryConsents.get(0);
        }
        Assert.assertEquals(maryConsent.getClient().getId(), fooClient.getId());
        Assert.assertEquals(maryConsent.getGrantedClientScopes().size(), 1);
        Assert.assertTrue(isClientScopeGranted(realm, "foo", maryConsent));
        Assert.assertEquals(maryHardcodedConsent.getClient().getId(), hardcodedClient.getId());
        Assert.assertEquals(maryHardcodedConsent.getGrantedClientScopes().size(), 0);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) UserConsentModel(org.keycloak.models.UserConsentModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

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