Search in sources :

Example 11 with RootAuthenticationSessionModel

use of org.keycloak.sessions.RootAuthenticationSessionModel in project keycloak by keycloak.

the class AuthenticationSessionTest method testLimitAuthSessions.

@Test
public void testLimitAuthSessions() {
    RootAuthenticationSessionModel ras = withRealm(realmId, (session, realm) -> session.authenticationSessions().createRootAuthenticationSession(realm));
    List<String> tabIds = withRealm(realmId, (session, realm) -> {
        ClientModel client = realm.getClientByClientId("test-app");
        return IntStream.range(0, 300).mapToObj(i -> {
            Time.setOffset(i);
            return ras.createAuthenticationSession(client);
        }).map(AuthenticationSessionModel::getTabId).collect(Collectors.toList());
    });
    withRealm(realmId, (session, realm) -> {
        ClientModel client = realm.getClientByClientId("test-app");
        // create 301st auth session
        AuthenticationSessionModel as = ras.createAuthenticationSession(client);
        Assert.assertEquals(as, ras.getAuthenticationSession(client, as.getTabId()));
        // assert the first authentication session was deleted
        Assert.assertNull(ras.getAuthenticationSession(client, tabIds.get(0)));
        return null;
    });
}
Also used : ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 12 with RootAuthenticationSessionModel

use of org.keycloak.sessions.RootAuthenticationSessionModel in project keycloak by keycloak.

the class AuthenticationSessionProviderTest method testOnRealmRemoved.

@Test
@ModelTest
public void testOnRealmRemoved(KeycloakSession session) {
    AtomicReference<String> authSessionID = new AtomicReference<>();
    AtomicReference<String> authSessionID2 = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
        KeycloakSession currentSession = sesRealmRemoved1;
        RealmModel realm = currentSession.realms().getRealm("test");
        RealmModel fooRealm = currentSession.realms().createRealm("foo-realm");
        fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
        fooRealm.addClient("foo-client");
        authSessionID.set(currentSession.authenticationSessions().createRootAuthenticationSession(realm).getId());
        authSessionID2.set(currentSession.authenticationSessions().createRootAuthenticationSession(fooRealm).getId());
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved2) -> {
        KeycloakSession currentSession = sesRealmRemoved2;
        new RealmManager(currentSession).removeRealm(currentSession.realms().getRealmByName("foo-realm"));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved3) -> {
        KeycloakSession currentSession = sesRealmRemoved3;
        RealmModel realm = currentSession.realms().getRealm("test");
        RootAuthenticationSessionModel authSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
        assertThat(authSession, notNullValue());
        assertThat(currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID2.get()), nullValue());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) KeycloakSession(org.keycloak.models.KeycloakSession) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 13 with RootAuthenticationSessionModel

use of org.keycloak.sessions.RootAuthenticationSessionModel in project keycloak by keycloak.

the class RestartLoginCookie method restartSession.

public static AuthenticationSessionModel restartSession(KeycloakSession session, RealmModel realm, RootAuthenticationSessionModel rootSession, String expectedClientId, Cookie cook) throws Exception {
    String encodedCookie = cook.getValue();
    RestartLoginCookie cookie = session.tokens().decode(encodedCookie, RestartLoginCookie.class);
    if (cookie == null) {
        logger.debug("Failed to verify encoded RestartLoginCookie");
        return null;
    }
    ClientModel client = realm.getClientByClientId(cookie.getClientId());
    if (client == null)
        return null;
    // Restart just if client from cookie matches client from the URL.
    if (!client.getClientId().equals(expectedClientId)) {
        logger.debugf("Skip restarting from the KC_RESTART. Clients doesn't match: Cookie client: %s, Requested client: %s", client.getClientId(), expectedClientId);
        return null;
    }
    // Need to create brand new session and setup cookie
    if (rootSession == null) {
        rootSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, true);
    }
    AuthenticationSessionModel authSession = rootSession.createAuthenticationSession(client);
    authSession.setProtocol(cookie.getAuthMethod());
    authSession.setRedirectUri(cookie.getRedirectUri());
    authSession.setAction(cookie.getAction());
    for (Map.Entry<String, String> entry : cookie.getNotes().entrySet()) {
        authSession.setClientNote(entry.getKey(), entry.getValue());
    }
    return authSession;
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) HashMap(java.util.HashMap) Map(java.util.Map)

Example 14 with RootAuthenticationSessionModel

use of org.keycloak.sessions.RootAuthenticationSessionModel 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 15 with RootAuthenticationSessionModel

use of org.keycloak.sessions.RootAuthenticationSessionModel in project keycloak by keycloak.

the class SessionCodeChecks method restartAuthenticationSessionFromCookie.

private Response restartAuthenticationSessionFromCookie(RootAuthenticationSessionModel existingRootSession) {
    logger.debug("Authentication session not found. Trying to restart from cookie.");
    AuthenticationSessionModel authSession = null;
    Cookie cook = RestartLoginCookie.getRestartCookie(session);
    if (cook == null) {
        event.error(Errors.COOKIE_NOT_FOUND);
        return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.COOKIE_NOT_FOUND);
    }
    try {
        authSession = RestartLoginCookie.restartSession(session, realm, existingRootSession, clientId, cook);
    } catch (Exception e) {
        ServicesLogger.LOGGER.failedToParseRestartLoginCookie(e);
    }
    if (authSession != null) {
        event.clone();
        event.detail(Details.RESTART_AFTER_TIMEOUT, "true");
        event.error(Errors.EXPIRED_CODE);
        String warningMessage = Messages.LOGIN_TIMEOUT;
        authSession.setAuthNote(LoginActionsService.FORWARDED_ERROR_MESSAGE_NOTE, warningMessage);
        String flowPath = authSession.getClientNote(AuthorizationEndpointBase.APP_INITIATED_FLOW);
        if (flowPath == null) {
            flowPath = LoginActionsService.AUTHENTICATE_PATH;
        }
        URI redirectUri = getLastExecutionUrl(flowPath, null, authSession.getTabId());
        logger.debugf("Authentication session restart from cookie succeeded. Redirecting to %s", redirectUri);
        return Response.status(Response.Status.FOUND).location(redirectUri).build();
    } else {
        // Finally need to show error as all the fallbacks failed
        event.error(Errors.INVALID_CODE);
        return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.INVALID_CODE);
    }
}
Also used : Cookie(javax.ws.rs.core.Cookie) RestartLoginCookie(org.keycloak.protocol.RestartLoginCookie) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) URI(java.net.URI)

Aggregations

RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)24 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)21 AuthenticationSessionManager (org.keycloak.services.managers.AuthenticationSessionManager)11 UserSessionModel (org.keycloak.models.UserSessionModel)10 ClientModel (org.keycloak.models.ClientModel)9 UserModel (org.keycloak.models.UserModel)9 ClientSessionContext (org.keycloak.models.ClientSessionContext)7 Test (org.junit.Test)6 RealmModel (org.keycloak.models.RealmModel)6 KeycloakSession (org.keycloak.models.KeycloakSession)5 DefaultClientSessionContext (org.keycloak.services.util.DefaultClientSessionContext)5 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 TokenManager (org.keycloak.protocol.oidc.TokenManager)3 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)3 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)3 Response (javax.ws.rs.core.Response)2 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)2 CorsErrorResponseException (org.keycloak.services.CorsErrorResponseException)2 ClientManager (org.keycloak.services.managers.ClientManager)2