Search in sources :

Example 91 with UserSessionModel

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

the class UserSessionPersisterProviderTest method testOnUserRemoved.

@Test
public void testOnUserRemoved() {
    int started = Time.currentTime();
    AtomicReference<UserSessionModel[]> origSessionsAt = new AtomicReference<>();
    inComittedTransaction(session -> {
        // Create some sessions in infinispan
        UserSessionModel[] origSessions = createSessions(session, realmId);
        origSessionsAt.set(origSessions);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionModel[] origSessions = origSessionsAt.get();
        // Persist 2 offline sessions of 2 users
        UserSessionModel userSession1 = session.sessions().getUserSession(realm, origSessions[1].getId());
        UserSessionModel userSession2 = session.sessions().getUserSession(realm, origSessions[2].getId());
        persistUserSession(session, userSession1, true);
        persistUserSession(session, userSession2, true);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        // Load offline sessions
        loadPersistedSessionsPaginated(session, true, 10, 1, 2);
        // Properly delete user and assert his offlineSession removed
        UserModel user1 = session.users().getUserByUsername(realm, "user1");
        new UserManager(session).removeUser(realm, user1);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        Assert.assertEquals(1, persister.getUserSessionsCount(true));
        List<UserSessionModel> loadedSessions = loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        UserSessionModel persistedSession = loadedSessions.get(0);
        assertSession(persistedSession, session.users().getUserByUsername(realm, "user2"), "127.0.0.3", started, started, "test-app");
        // KEYCLOAK-2431 Assert that userSessionPersister is resistent even to situation, when users are deleted "directly".
        // No exception will happen. However session will be still there
        UserModel user2 = session.users().getUserByUsername(realm, "user2");
        session.users().removeUser(realm, user2);
        loadedSessions = loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        // Cleanup
        UserSessionModel userSession = loadedSessions.get(0);
        session.sessions().removeUserSession(realm, userSession);
        persister.removeUserSession(userSession.getId(), userSession.isOffline());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) UserManager(org.keycloak.models.UserManager) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 92 with UserSessionModel

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

the class OfflinePersistentUserSessionLoader method loadSessions.

@Override
public OfflinePersistentWorkerResult loadSessions(KeycloakSession session, OfflinePersistentLoaderContext loaderContext, OfflinePersistentWorkerContext ctx) {
    int first = ctx.getWorkerId() * sessionsPerSegment;
    log.tracef("Loading sessions for segment=%d lastSessionId=%s", ctx.getSegment(), ctx.getLastSessionId());
    UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
    List<UserSessionModel> sessions = persister.loadUserSessionsStream(first, sessionsPerSegment, true, ctx.getLastSessionId()).collect(Collectors.toList());
    log.tracef("Sessions loaded from DB - segment=%d lastSessionId=%s", ctx.getSegment(), ctx.getLastSessionId());
    UserSessionModel lastSession = null;
    if (!sessions.isEmpty()) {
        lastSession = sessions.get(sessions.size() - 1);
        // Save to memory/infinispan
        session.sessions().importUserSessions(sessions, true);
    }
    String lastSessionId = lastSession == null ? FIRST_SESSION_ID : lastSession.getId();
    log.tracef("Sessions imported to infinispan - segment: %d, lastSessionId: %s", ctx.getSegment(), lastSessionId);
    return new OfflinePersistentWorkerResult(true, ctx.getSegment(), ctx.getWorkerId(), lastSessionId);
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider)

Example 93 with UserSessionModel

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

the class ScriptBasedOIDCProtocolMapper method evaluateScript.

private Object evaluateScript(Object tokenBinding, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession) {
    UserModel user = userSession.getUser();
    String scriptSource = getScriptCode(mappingModel);
    RealmModel realm = userSession.getRealm();
    ScriptingProvider scripting = keycloakSession.getProvider(ScriptingProvider.class);
    ScriptModel scriptModel = scripting.createScript(realm.getId(), ScriptModel.TEXT_JAVASCRIPT, "token-mapper-script_" + mappingModel.getName(), scriptSource, null);
    EvaluatableScriptAdapter script = scripting.prepareEvaluatableScript(scriptModel);
    Object claimValue;
    try {
        claimValue = script.eval((bindings) -> {
            bindings.put("user", user);
            bindings.put("realm", realm);
            if (tokenBinding instanceof IDToken) {
                bindings.put("token", tokenBinding);
            } else if (tokenBinding instanceof AccessTokenResponse) {
                bindings.put("tokenResponse", tokenBinding);
            }
            bindings.put("userSession", userSession);
            bindings.put("keycloakSession", keycloakSession);
        });
    } catch (Exception ex) {
        LOGGER.error("Error during execution of ProtocolMapper script", ex);
        claimValue = null;
    }
    return claimValue;
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) ScriptModel(org.keycloak.models.ScriptModel) ProtocolMapperContainerModel(org.keycloak.models.ProtocolMapperContainerModel) RealmModel(org.keycloak.models.RealmModel) Profile(org.keycloak.common.Profile) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel) ProtocolMapperConfigException(org.keycloak.protocol.ProtocolMapperConfigException) Logger(org.jboss.logging.Logger) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) KeycloakSession(org.keycloak.models.KeycloakSession) UserSessionModel(org.keycloak.models.UserSessionModel) EnvironmentDependentProviderFactory(org.keycloak.provider.EnvironmentDependentProviderFactory) IDToken(org.keycloak.representations.IDToken) ProviderConfigurationBuilder(org.keycloak.provider.ProviderConfigurationBuilder) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) ScriptModel(org.keycloak.models.ScriptModel) EvaluatableScriptAdapter(org.keycloak.scripting.EvaluatableScriptAdapter) List(java.util.List) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) ScriptingProvider(org.keycloak.scripting.ScriptingProvider) ScriptCompilationException(org.keycloak.scripting.ScriptCompilationException) ProtocolMapperUtils(org.keycloak.protocol.ProtocolMapperUtils) ScriptingProvider(org.keycloak.scripting.ScriptingProvider) EvaluatableScriptAdapter(org.keycloak.scripting.EvaluatableScriptAdapter) IDToken(org.keycloak.representations.IDToken) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) ProtocolMapperConfigException(org.keycloak.protocol.ProtocolMapperConfigException) ScriptCompilationException(org.keycloak.scripting.ScriptCompilationException)

Example 94 with UserSessionModel

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

the class FullNameMapper method setClaim.

protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    List<String> parts = new LinkedList<>();
    Optional.ofNullable(user.getFirstName()).filter(s -> !s.isEmpty()).ifPresent(parts::add);
    Optional.ofNullable(user.getLastName()).filter(s -> !s.isEmpty()).ifPresent(parts::add);
    if (!parts.isEmpty()) {
        token.getOtherClaims().put("name", String.join(" ", parts));
    }
}
Also used : UserModel(org.keycloak.models.UserModel) List(java.util.List) UserModel(org.keycloak.models.UserModel) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel) Map(java.util.Map) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) HashMap(java.util.HashMap) UserSessionModel(org.keycloak.models.UserSessionModel) LinkedList(java.util.LinkedList) IDToken(org.keycloak.representations.IDToken) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList)

Example 95 with UserSessionModel

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

the class IdentityBrokerService method authenticated.

public Response authenticated(BrokeredIdentityContext context) {
    IdentityProviderModel identityProviderConfig = context.getIdpConfig();
    AuthenticationSessionModel authenticationSession = context.getAuthenticationSession();
    String providerId = identityProviderConfig.getAlias();
    if (!identityProviderConfig.isStoreToken()) {
        if (isDebugEnabled()) {
            logger.debugf("Token will not be stored for identity provider [%s].", providerId);
        }
        context.setToken(null);
    }
    StatusResponseType loginResponse = (StatusResponseType) context.getContextData().get(SAMLEndpoint.SAML_LOGIN_RESPONSE);
    if (loginResponse != null) {
        for (Iterator<SamlAuthenticationPreprocessor> it = SamlSessionUtils.getSamlAuthenticationPreprocessorIterator(session); it.hasNext(); ) {
            loginResponse = it.next().beforeProcessingLoginResponse(loginResponse, authenticationSession);
        }
    }
    session.getContext().setClient(authenticationSession.getClient());
    context.getIdp().preprocessFederatedIdentity(session, realmModel, context);
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    realmModel.getIdentityProviderMappersByAliasStream(context.getIdpConfig().getAlias()).forEach(mapper -> {
        IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
        target.preprocessFederatedIdentity(session, realmModel, mapper, context);
    });
    FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(providerId, context.getId(), context.getUsername(), context.getToken());
    this.event.event(EventType.IDENTITY_PROVIDER_LOGIN).detail(Details.REDIRECT_URI, authenticationSession.getRedirectUri()).detail(Details.IDENTITY_PROVIDER, providerId).detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
    UserModel federatedUser = this.session.users().getUserByFederatedIdentity(this.realmModel, federatedIdentityModel);
    boolean shouldMigrateId = false;
    // try to find the user using legacy ID
    if (federatedUser == null && context.getLegacyId() != null) {
        federatedIdentityModel = new FederatedIdentityModel(federatedIdentityModel, context.getLegacyId());
        federatedUser = this.session.users().getUserByFederatedIdentity(this.realmModel, federatedIdentityModel);
        shouldMigrateId = true;
    }
    // Check if federatedUser is already authenticated (this means linking social into existing federatedUser account)
    UserSessionModel userSession = new AuthenticationSessionManager(session).getUserSession(authenticationSession);
    if (shouldPerformAccountLinking(authenticationSession, userSession, providerId)) {
        return performAccountLinking(authenticationSession, userSession, context, federatedIdentityModel, federatedUser);
    }
    if (federatedUser == null) {
        logger.debugf("Federated user not found for provider '%s' and broker username '%s'", providerId, context.getUsername());
        String username = context.getModelUsername();
        if (username == null) {
            if (this.realmModel.isRegistrationEmailAsUsername() && !Validation.isBlank(context.getEmail())) {
                username = context.getEmail();
            } else if (context.getUsername() == null) {
                username = context.getIdpConfig().getAlias() + "." + context.getId();
            } else {
                username = context.getUsername();
            }
        }
        username = username.trim();
        context.setModelUsername(username);
        SerializedBrokeredIdentityContext ctx0 = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        if (ctx0 != null) {
            SerializedBrokeredIdentityContext ctx1 = SerializedBrokeredIdentityContext.serialize(context);
            ctx1.saveToAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT);
            logger.warnv("Nested first broker flow detected: {0} -> {1}", ctx0.getIdentityProviderId(), ctx1.getIdentityProviderId());
            logger.debug("Resuming last execution");
            URI redirect = new AuthenticationFlowURLHelper(session, realmModel, session.getContext().getUri()).getLastExecutionUrl(authenticationSession);
            return Response.status(Status.FOUND).location(redirect).build();
        }
        logger.debug("Redirecting to flow for firstBrokerLogin");
        boolean forwardedPassiveLogin = "true".equals(authenticationSession.getAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN));
        // Redirect to firstBrokerLogin after successful login and ensure that previous authentication state removed
        AuthenticationProcessor.resetFlow(authenticationSession, LoginActionsService.FIRST_BROKER_LOGIN_PATH);
        // Set the FORWARDED_PASSIVE_LOGIN note (if needed) after resetting the session so it is not lost.
        if (forwardedPassiveLogin) {
            authenticationSession.setAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN, "true");
        }
        SerializedBrokeredIdentityContext ctx = SerializedBrokeredIdentityContext.serialize(context);
        ctx.saveToAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        URI redirect = LoginActionsService.firstBrokerLoginProcessor(session.getContext().getUri()).queryParam(Constants.CLIENT_ID, authenticationSession.getClient().getClientId()).queryParam(Constants.TAB_ID, authenticationSession.getTabId()).build(realmModel.getName());
        return Response.status(302).location(redirect).build();
    } else {
        Response response = validateUser(authenticationSession, federatedUser, realmModel);
        if (response != null) {
            return response;
        }
        updateFederatedIdentity(context, federatedUser);
        if (shouldMigrateId) {
            migrateFederatedIdentityId(context, federatedUser);
        }
        authenticationSession.setAuthenticatedUser(federatedUser);
        return finishOrRedirectToPostBrokerLogin(authenticationSession, context, false);
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) AuthenticationFlowURLHelper(org.keycloak.services.util.AuthenticationFlowURLHelper) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) URI(java.net.URI) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) UserModel(org.keycloak.models.UserModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) SamlAuthenticationPreprocessor(org.keycloak.protocol.saml.preprocessor.SamlAuthenticationPreprocessor)

Aggregations

UserSessionModel (org.keycloak.models.UserSessionModel)133 RealmModel (org.keycloak.models.RealmModel)68 Test (org.junit.Test)53 ClientModel (org.keycloak.models.ClientModel)44 UserModel (org.keycloak.models.UserModel)43 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)38 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)29 KeycloakSession (org.keycloak.models.KeycloakSession)26 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)26 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)21 ClientSessionContext (org.keycloak.models.ClientSessionContext)20 AtomicReference (java.util.concurrent.atomic.AtomicReference)18 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)17 KeycloakModelTest (org.keycloak.testsuite.model.KeycloakModelTest)17 Response (javax.ws.rs.core.Response)15 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)14 List (java.util.List)13 CorsErrorResponseException (org.keycloak.services.CorsErrorResponseException)13 Map (java.util.Map)12 UserSessionPersisterProvider (org.keycloak.models.session.UserSessionPersisterProvider)12