Search in sources :

Example 51 with UserSessionModel

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

the class SessionStateChecker method run.

public static void run(KeycloakTestingClient.Server server, String realmName, AtomicReference<String> userSessionIdStore, AtomicReference<String> expectedUserSession, String expectedClientSession, SerializableConsumer<UserSessionModel> consumeUserSession, Map<String, SerializableConsumer<AuthenticatedClientSessionModel>> consumeClientSession, SerializableFunction<KeycloakSession, String> userSessionIdProvider, SerializableFunction<KeycloakSession, String> clientSessionIdProvider) {
    if (server == null || userSessionIdProvider == null)
        throw new RuntimeException("Wrongly configured session checker");
    if (userSessionIdStore != null) {
        String userSession = server.fetchString((FetchOnServer) userSessionIdProvider::apply);
        userSessionIdStore.set(userSession.replace("\"", ""));
    }
    server.run(session -> {
        String sessionId = userSessionIdProvider.apply(session);
        if (expectedUserSession != null) {
            assertThat(sessionId, equalTo(expectedUserSession.get()));
        }
        if (expectedClientSession != null) {
            String clientSession = clientSessionIdProvider.apply(session);
            assertThat(clientSession, equalTo(expectedClientSession));
        }
        RealmModel realm = session.realms().getRealmByName(realmName);
        UserSessionModel userSessionModel = session.sessions().getUserSession(realm, sessionId);
        if (consumeUserSession != null)
            consumeUserSession.accept(userSessionModel);
        if (!consumeClientSession.isEmpty()) {
            consumeClientSession.forEach((id, consumer) -> consumer.accept(userSessionModel.getAuthenticatedClientSessionByClient(id)));
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel)

Example 52 with UserSessionModel

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

the class ArtifactBindingTest method testSessionStateDuringArtifactBindingLogoutWithOneClient.

// Won't work with openshift, because openshift wouldn't see ArtifactResolutionService
@AuthServerContainerExclude(AuthServerContainerExclude.AuthServer.REMOTE)
@Test
public void testSessionStateDuringArtifactBindingLogoutWithOneClient() {
    ClientRepresentation salesRep = adminClient.realm(REALM_NAME).clients().findByClientId(SAML_CLIENT_ID_SALES_POST).get(0);
    final String clientId = salesRep.getId();
    getCleanup().addCleanup(ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_SALES_POST).setAttribute(SamlConfigAttributes.SAML_ARTIFACT_BINDING, "true").setAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_ARTIFACT_ATTRIBUTE, "http://url").setFrontchannelLogout(true).update());
    AtomicReference<String> userSessionId = new AtomicReference<>();
    SAMLDocumentHolder response = new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, POST).build().login().user(bburkeUser).build().handleArtifact(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST).setBeforeStepChecks(new SessionStateChecker(testingClient.server()).storeUserSessionId(userSessionId).expectedState(UserSessionModel.State.LOGGED_IN).expectedClientSession(clientId).consumeUserSession(userSessionModel -> assertThat(userSessionModel, notNullValue())).consumeClientSession(clientId, userSessionModel -> assertThat(userSessionModel, notNullValue()))).build().logoutRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, POST).build().handleArtifact(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST).setBeforeStepChecks(new SessionStateChecker(testingClient.server()).expectedUserSession(userSessionId).expectedState(UserSessionModel.State.LOGGED_OUT_UNCONFIRMED).expectedNumberOfClientSessions(1).expectedAction(clientId, CommonClientSessionModel.Action.LOGGING_OUT)).setAfterStepChecks(new SessionStateChecker(testingClient.server()).consumeUserSession(userSessionModel -> assertThat(userSessionModel, nullValue())).setUserSessionProvider(session -> userSessionId.get())).build().doNotFollowRedirects().executeAndTransform(this::getArtifactResponse);
    assertThat(response.getSamlObject(), instanceOf(ArtifactResponseType.class));
    ArtifactResponseType artifactResponse = (ArtifactResponseType) response.getSamlObject();
    assertThat(artifactResponse, isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    assertThat(artifactResponse.getSignature(), nullValue());
    assertThat(artifactResponse.getAny(), not(instanceOf(ResponseType.class)));
    assertThat(artifactResponse.getAny(), not(instanceOf(ArtifactResponseType.class)));
    assertThat(artifactResponse.getAny(), not(instanceOf(NameIDMappingResponseType.class)));
    assertThat(artifactResponse.getAny(), instanceOf(StatusResponseType.class));
    StatusResponseType samlResponse = (StatusResponseType) artifactResponse.getAny();
    assertThat(samlResponse, isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
}
Also used : SamlProtocolUtils(org.keycloak.protocol.saml.SamlProtocolUtils) AssertionUtil(org.keycloak.saml.processing.core.saml.v2.util.AssertionUtil) ClientAttributeUpdater(org.keycloak.testsuite.updaters.ClientAttributeUpdater) Matchers.statusCodeIsHC(org.keycloak.testsuite.util.Matchers.statusCodeIsHC) URISyntaxException(java.net.URISyntaxException) Matchers.not(org.hamcrest.Matchers.not) ARTIFACT_RESPONSE(org.keycloak.testsuite.util.SamlClient.Binding.ARTIFACT_RESPONSE) POST(org.keycloak.testsuite.util.SamlClient.Binding.POST) SAML2LogoutResponseBuilder(org.keycloak.saml.SAML2LogoutResponseBuilder) Matchers.isSamlLogoutRequest(org.keycloak.testsuite.util.Matchers.isSamlLogoutRequest) HandleArtifactStepBuilder(org.keycloak.testsuite.util.saml.HandleArtifactStepBuilder) EntityUtils(org.apache.http.util.EntityUtils) InfinispanTestTimeServiceRule(org.keycloak.testsuite.util.InfinispanTestTimeServiceRule) SAML2Object(org.keycloak.dom.saml.v2.SAML2Object) Matcher(java.util.regex.Matcher) ByteArrayInputStream(java.io.ByteArrayInputStream) Document(org.w3c.dom.Document) NameIDMappingResponseType(org.keycloak.dom.saml.v2.protocol.NameIDMappingResponseType) Matchers.nullValue(org.hamcrest.Matchers.nullValue) SamlClient(org.keycloak.testsuite.util.SamlClient) SamlUtils(org.keycloak.testsuite.util.SamlUtils) URI(java.net.URI) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) Matchers.isEmptyOrNullString(org.hamcrest.Matchers.isEmptyOrNullString) Awaitility.await(org.awaitility.Awaitility.await) Matchers.isSamlResponse(org.keycloak.testsuite.util.Matchers.isSamlResponse) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) ArtifactResponseType(org.keycloak.dom.saml.v2.protocol.ArtifactResponseType) SamlProtocol(org.keycloak.protocol.saml.SamlProtocol) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) IOUtil(org.keycloak.testsuite.utils.io.IOUtil) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) Base64(java.util.Base64) Response(javax.ws.rs.core.Response) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Matchers.isSamlStatusResponse(org.keycloak.testsuite.util.Matchers.isSamlStatusResponse) SamlMessageReceiver(org.keycloak.testsuite.util.saml.SamlMessageReceiver) Matchers.is(org.hamcrest.Matchers.is) Pattern(java.util.regex.Pattern) Matchers.containsString(org.hamcrest.Matchers.containsString) SamlUtils.getSPInstallationDescriptor(org.keycloak.testsuite.util.SamlUtils.getSPInstallationDescriptor) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) SAMLParser(org.keycloak.saml.processing.core.parsers.saml.SAMLParser) DOMSource(javax.xml.transform.dom.DOMSource) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) SAML2Request(org.keycloak.saml.processing.api.saml.v2.request.SAML2Request) MessageDigest(java.security.MessageDigest) GeneralConstants(org.keycloak.saml.common.constants.GeneralConstants) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) SamlConfigAttributes(org.keycloak.protocol.saml.SamlConfigAttributes) Matchers.bodyHC(org.keycloak.testsuite.util.Matchers.bodyHC) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArtifactBindingUtils(org.keycloak.protocol.saml.util.ArtifactBindingUtils) REDIRECT(org.keycloak.testsuite.util.SamlClient.Binding.REDIRECT) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) CommonClientSessionModel(org.keycloak.sessions.CommonClientSessionModel) Soap(org.keycloak.protocol.saml.profile.util.Soap) Charsets(com.google.common.base.Charsets) SPSSODescriptorType(org.keycloak.dom.saml.v2.metadata.SPSSODescriptorType) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) IOException(java.io.IOException) UserSessionModel(org.keycloak.models.UserSessionModel) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) TimeUnit(java.util.concurrent.TimeUnit) Rule(org.junit.Rule) SamlDeployment(org.keycloak.adapters.saml.SamlDeployment) SessionStateChecker(org.keycloak.testsuite.util.saml.SessionStateChecker) LogoutRequestType(org.keycloak.dom.saml.v2.protocol.LogoutRequestType) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArtifactResponseType(org.keycloak.dom.saml.v2.protocol.ArtifactResponseType) Matchers.isEmptyOrNullString(org.hamcrest.Matchers.isEmptyOrNullString) Matchers.containsString(org.hamcrest.Matchers.containsString) SessionStateChecker(org.keycloak.testsuite.util.saml.SessionStateChecker) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test)

Example 53 with UserSessionModel

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

the class DeviceActivityTest method ipTest.

@Test
public void ipTest() {
    final String ip = "146.58.69.12";
    String sessionId = "abcdefg";
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(TEST);
        ClientModel client = session.clientLocalStorage().getClientByClientId(TEST_CLIENT_ID, realm);
        // cannot use testUser.getUsername() because it throws NotSerializableException for no apparent reason (or maybe I'm just stupid :D)
        UserModel user = session.users().getUserByUsername("test", realm);
        UserSessionModel userSession = session.sessions().createUserSession(sessionId, realm, user, "test", ip, "form", false, null, null, null);
        session.sessions().createClientSession(realm, client, userSession);
    });
    deviceActivityPage.clickRefreshPage();
    assertEquals(ip, deviceActivityPage.getSession(sessionId).getIp());
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) Test(org.junit.Test)

Example 54 with UserSessionModel

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

the class DeviceActivityTest method clientsTest.

@Test
public void clientsTest() {
    String sessionId = createSession(Browsers.CHROME);
    // attach more clients to the session
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(TEST);
        UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
        ClientModel client2 = session.clientLocalStorage().getClientByClientId(TEST_CLIENT2_ID, realm);
        ClientModel client3 = session.clientLocalStorage().getClientByClientId(TEST_CLIENT3_ID, realm);
        session.sessions().createClientSession(realm, client2, userSession);
        session.sessions().createClientSession(realm, client3, userSession);
    });
    deviceActivityPage.clickRefreshPage();
    List<String> expectedClients = Arrays.asList(TEST_CLIENT_ID, LOCALE_CLIENT_NAME_LOCALIZED, TEST_CLIENT3_NAME);
    String[] actualClients = deviceActivityPage.getSession(sessionId).getClients().split(", ");
    assertThat(expectedClients, containsInAnyOrder(actualClients));
    assertEquals("Account Console", deviceActivityPage.getSessionByIndex(0).getClients());
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) Test(org.junit.Test)

Example 55 with UserSessionModel

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

the class UserSessionPersisterProviderTest method testOnClientRemoved.

@Test
public void testOnClientRemoved() {
    int started = Time.currentTime();
    AtomicReference<String> userSessionID = new AtomicReference<>();
    inComittedTransaction(session -> {
        RealmModel fooRealm = session.realms().createRealm("foo", "foo");
        fooRealm.setDefaultRole(session.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX));
        fooRealm.addClient("foo-app");
        fooRealm.addClient("bar-app");
        session.users().addUser(fooRealm, "user3");
        UserSessionModel userSession = session.sessions().createUserSession(fooRealm, session.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
        userSessionID.set(userSession.getId());
        createClientSession(session, realmId, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
        createClientSession(session, realmId, fooRealm.getClientByClientId("bar-app"), userSession, "http://redirect", "state");
    });
    inComittedTransaction(session -> {
        RealmModel fooRealm = session.realms().getRealm("foo");
        // Persist offline session
        UserSessionModel userSession = session.sessions().getUserSession(fooRealm, userSessionID.get());
        persistUserSession(session, userSession, true);
    });
    inComittedTransaction(session -> {
        RealmManager realmMgr = new RealmManager(session);
        ClientManager clientMgr = new ClientManager(realmMgr);
        RealmModel fooRealm = realmMgr.getRealm("foo");
        // Assert session was persisted with both clientSessions
        UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
        assertSession(persistedSession, session.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app");
        // Remove foo-app client
        ClientModel client = fooRealm.getClientByClientId("foo-app");
        clientMgr.removeClient(fooRealm, client);
    });
    inComittedTransaction(session -> {
        RealmManager realmMgr = new RealmManager(session);
        ClientManager clientMgr = new ClientManager(realmMgr);
        RealmModel fooRealm = realmMgr.getRealm("foo");
        // Assert just one bar-app clientSession persisted now
        UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
        assertSession(persistedSession, session.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "bar-app");
        // Remove bar-app client
        ClientModel client = fooRealm.getClientByClientId("bar-app");
        clientMgr.removeClient(fooRealm, client);
    });
    inComittedTransaction(session -> {
        // Assert loading still works - last userSession is still there, but no clientSession on it
        loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        // Cleanup
        RealmManager realmMgr = new RealmManager(session);
        realmMgr.removeRealm(realmMgr.getRealm("foo"));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) ClientManager(org.keycloak.services.managers.ClientManager) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

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