Search in sources :

Example 81 with UserSessionModel

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

the class CacheTest method testAddUserNotAddedToCache.

@Test
public void testAddUserNotAddedToCache() {
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        UserModel user = session.users().addUser(realm, "testAddUserNotAddedToCache");
        user.setFirstName("firstName");
        user.addRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP);
        UserSessionModel userSession = session.sessions().createUserSession(UUID.randomUUID().toString(), realm, user, "testAddUserNotAddedToCache", "127.0.0.1", "auth", false, null, null, UserSessionModel.SessionPersistenceState.PERSISTENT);
        user = userSession.getUser();
        user.setLastName("lastName");
        assertNotNull(user.getLastName());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserSessionModel(org.keycloak.models.UserSessionModel) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 82 with UserSessionModel

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

the class DeviceActivityTest method timesTests.

@Test
public void timesTests() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy, h:mm a", Locale.ENGLISH);
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime nowPlus1 = now.plusMinutes(1);
    String nowStr = now.format(formatter);
    String nowStrPlus1 = nowPlus1.format(formatter);
    String sessionId = createSession(Browsers.CHROME);
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(TEST);
        UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
        userSession.setLastSessionRefresh(Time.currentTime() + 120);
    });
    deviceActivityPage.clickRefreshPage();
    DeviceActivityPage.Session session = deviceActivityPage.getSession(sessionId);
    String startedAtStr = session.getStarted();
    LocalDateTime startedAt = LocalDateTime.parse(startedAtStr, formatter);
    LocalDateTime lastAccessed = LocalDateTime.parse(session.getLastAccess(), formatter);
    LocalDateTime expiresAt = LocalDateTime.parse(session.getExpires(), formatter);
    assertTrue("Last access should be after started at", lastAccessed.isAfter(startedAt));
    assertTrue("Expires at should be after last access", expiresAt.isAfter(lastAccessed));
    assertTrue("Last accessed should be in the future", lastAccessed.isAfter(now));
    assertThat(startedAtStr, either(equalTo(nowStr)).or(equalTo(nowStrPlus1)));
    int ssoLifespan = testRealmResource().toRepresentation().getSsoSessionMaxLifespan();
    assertEquals(startedAt.plusSeconds(ssoLifespan), expiresAt);
}
Also used : LocalDateTime(java.time.LocalDateTime) RealmModel(org.keycloak.models.RealmModel) DeviceActivityPage(org.keycloak.testsuite.ui.account2.page.DeviceActivityPage) UserSessionModel(org.keycloak.models.UserSessionModel) DateTimeFormatter(java.time.format.DateTimeFormatter) Test(org.junit.Test)

Example 83 with UserSessionModel

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

the class LoginActionsServiceChecks method checkNotLoggedInYet.

/**
 * Verifies that the authentication session has not yet been converted to user session, in other words
 * that the user has not yet completed authentication and logged in.
 */
public static <T extends JsonWebToken> void checkNotLoggedInYet(ActionTokenContext<T> context, AuthenticationSessionModel authSessionFromCookie, String authSessionId) throws VerificationException {
    if (authSessionId == null) {
        return;
    }
    UserSessionModel userSession = context.getSession().sessions().getUserSession(context.getRealm(), authSessionId);
    boolean hasNoRequiredActions = (userSession == null || userSession.getUser().getRequiredActionsStream().count() == 0) && (authSessionFromCookie == null || authSessionFromCookie.getRequiredActions() == null || authSessionFromCookie.getRequiredActions().isEmpty());
    if (userSession != null && hasNoRequiredActions) {
        LoginFormsProvider loginForm = context.getSession().getProvider(LoginFormsProvider.class).setAuthenticationSession(context.getAuthenticationSession()).setSuccess(Messages.ALREADY_LOGGED_IN);
        if (context.getSession().getContext().getClient() == null) {
            loginForm.setAttribute(Constants.SKIP_LINK, true);
        }
        throw new LoginActionsServiceException(loginForm.createInfoPage());
    }
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider)

Example 84 with UserSessionModel

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

the class SessionCodeChecks method initialVerifyAuthSession.

public AuthenticationSessionModel initialVerifyAuthSession() {
    // Basic realm checks
    if (!checkSsl()) {
        event.error(Errors.SSL_REQUIRED);
        response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
        return null;
    }
    if (!realm.isEnabled()) {
        event.error(Errors.REALM_DISABLED);
        response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
        return null;
    }
    // Setup client to be shown on error/info page based on "client_id" parameter
    logger.debugf("Will use client '%s' in back-to-application link", clientId);
    ClientModel client = null;
    if (clientId != null) {
        client = realm.getClientByClientId(clientId);
    }
    if (client != null) {
        session.getContext().setClient(client);
    }
    // object retrieve
    AuthenticationSessionManager authSessionManager = new AuthenticationSessionManager(session);
    AuthenticationSessionModel authSession = null;
    if (authSessionId != null)
        authSession = authSessionManager.getAuthenticationSessionByIdAndClient(realm, authSessionId, client, tabId);
    AuthenticationSessionModel authSessionCookie = authSessionManager.getCurrentAuthenticationSession(realm, client, tabId);
    if (authSession != null && authSessionCookie != null && !authSession.getParentSession().getId().equals(authSessionCookie.getParentSession().getId())) {
        event.detail(Details.REASON, "cookie does not match auth_session query parameter");
        event.error(Errors.INVALID_CODE);
        response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_CODE);
        return null;
    }
    if (authSession != null) {
        session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession);
        return authSession;
    }
    if (authSessionCookie != null) {
        session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSessionCookie);
        return authSessionCookie;
    }
    // See if we are already authenticated and userSession with same ID exists.
    UserSessionModel userSession = authSessionManager.getUserSessionFromAuthCookie(realm);
    if (userSession != null) {
        LoginFormsProvider loginForm = session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.ALREADY_LOGGED_IN);
        if (client == null) {
            loginForm.setAttribute(Constants.SKIP_LINK, true);
        }
        response = loginForm.createInfoPage();
        return null;
    }
    // Otherwise just try to restart from the cookie
    RootAuthenticationSessionModel existingRootAuthSession = authSessionManager.getCurrentRootAuthenticationSession(realm);
    response = restartAuthenticationSessionFromCookie(existingRootAuthSession);
    return null;
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) UserSessionModel(org.keycloak.models.UserSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel)

Example 85 with UserSessionModel

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

the class LoginActionsService method restartSession.

/**
 * protocol independent page for restart of the flow
 *
 * @return
 */
@Path(RESTART_PATH)
@GET
public // optional, can get from cookie instead
Response restartSession(// optional, can get from cookie instead
@QueryParam(AUTH_SESSION_ID) String authSessionId, @QueryParam(Constants.CLIENT_ID) String clientId, @QueryParam(Constants.TAB_ID) String tabId) {
    event.event(EventType.RESTART_AUTHENTICATION);
    SessionCodeChecks checks = new SessionCodeChecks(realm, session.getContext().getUri(), request, clientConnection, session, event, authSessionId, null, null, clientId, tabId, null);
    AuthenticationSessionModel authSession = checks.initialVerifyAuthSession();
    if (authSession == null) {
        return checks.getResponse();
    }
    String flowPath = authSession.getClientNote(AuthorizationEndpointBase.APP_INITIATED_FLOW);
    if (flowPath == null) {
        flowPath = AUTHENTICATE_PATH;
    }
    // See if we already have userSession attached to authentication session. This means restart of authentication session during re-authentication
    // We logout userSession in this case
    UserSessionModel userSession = new AuthenticationSessionManager(session).getUserSession(authSession);
    if (userSession != null) {
        logger.debugf("Logout of user session %s when restarting flow during re-authentication", userSession.getId());
        AuthenticationManager.backchannelLogout(session, userSession, false);
    }
    AuthenticationProcessor.resetFlow(authSession, flowPath);
    URI redirectUri = getLastExecutionUrl(flowPath, null, authSession.getClient().getClientId(), tabId);
    logger.debugf("Flow restart requested. Redirecting to %s", redirectUri);
    return Response.status(Response.Status.FOUND).location(redirectUri).build();
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) URI(java.net.URI) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

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