Search in sources :

Example 11 with UserSessionRepresentation

use of org.keycloak.representations.idm.UserSessionRepresentation in project keycloak by keycloak.

the class ConsentsTest method testConsents.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testConsents() {
    driver.navigate().to(getAccountUrl(consumerRealmName()));
    log.debug("Clicking social " + getIDPAlias());
    accountLoginPage.clickSocial(getIDPAlias());
    if (!driver.getCurrentUrl().contains("/auth/realms/" + providerRealmName() + "/")) {
        log.debug("Not on provider realm page, url: " + driver.getCurrentUrl());
    }
    Assert.assertTrue("Driver should be on the provider realm page right now", driver.getCurrentUrl().contains("/auth/realms/" + providerRealmName() + "/"));
    log.debug("Logging in");
    accountLoginPage.login(getUserLogin(), getUserPassword());
    waitForPage("grant access");
    Assert.assertTrue(consentPage.isCurrent());
    consentPage.confirm();
    Assert.assertTrue("We must be on correct realm right now", driver.getCurrentUrl().contains("/auth/realms/" + consumerRealmName() + "/"));
    UsersResource consumerUsers = adminClient.realm(consumerRealmName()).users();
    Assert.assertTrue("There must be at least one user", consumerUsers.count() > 0);
    List<UserRepresentation> users = consumerUsers.search("", 0, 5);
    UserRepresentation foundUser = null;
    for (UserRepresentation user : users) {
        if (user.getUsername().equals(getUserLogin()) && user.getEmail().equals(getUserEmail())) {
            foundUser = user;
            break;
        }
    }
    Assert.assertNotNull("There must be user " + getUserLogin() + " in realm " + consumerRealmName(), foundUser);
    // get user with the same username from provider realm
    RealmResource providerRealm = adminClient.realm(providerRealmName());
    users = providerRealm.users().search(null, foundUser.getFirstName(), foundUser.getLastName(), null, 0, 1);
    Assert.assertEquals("Same user should be in provider realm", 1, users.size());
    String userId = users.get(0).getId();
    UserResource userResource = providerRealm.users().get(userId);
    // list consents
    List<Map<String, Object>> consents = userResource.getConsents();
    Assert.assertEquals("There should be one consent", 1, consents.size());
    Map<String, Object> consent = consents.get(0);
    Assert.assertEquals("Consent should be given to " + CLIENT_ID, CLIENT_ID, consent.get("clientId"));
    // list sessions. Single client should be in user session
    List<UserSessionRepresentation> sessions = userResource.getUserSessions();
    Assert.assertEquals("There should be one active session", 1, sessions.size());
    Assert.assertEquals("There should be one client in user session", 1, sessions.get(0).getClients().size());
    // revoke consent
    userResource.revokeConsent(CLIENT_ID);
    // list consents
    consents = userResource.getConsents();
    Assert.assertEquals("There should be no consents", 0, consents.size());
    // list sessions
    sessions = userResource.getUserSessions();
    Assert.assertEquals("There should be one active session", 1, sessions.size());
    Assert.assertEquals("There should be no client in user session", 0, sessions.get(0).getClients().size());
}
Also used : UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) UsersResource(org.keycloak.admin.client.resource.UsersResource) UserResource(org.keycloak.admin.client.resource.UserResource) Map(java.util.Map) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 12 with UserSessionRepresentation

use of org.keycloak.representations.idm.UserSessionRepresentation in project keycloak by keycloak.

the class SessionExpirationCrossDCTest method testLogoutUser.

@Test
public void testLogoutUser(@JmxInfinispanCacheStatistics(dc = DC.FIRST, managementPortProperty = "cache.server.management.port", cacheName = InfinispanConnectionProvider.USER_SESSION_CACHE_NAME) InfinispanStatistics cacheDc1Statistics, @JmxInfinispanCacheStatistics(dc = DC.SECOND, managementPortProperty = "cache.server.2.management.port", cacheName = InfinispanConnectionProvider.USER_SESSION_CACHE_NAME) InfinispanStatistics cacheDc2Statistics, @JmxInfinispanChannelStatistics() InfinispanStatistics channelStatisticsCrossDc) throws Exception {
    createInitialSessions(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME, InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME, false, cacheDc1Statistics, cacheDc2Statistics, true);
    channelStatisticsCrossDc.reset();
    // Logout single session of user first
    UserResource user = ApiUtil.findUserByUsernameId(getAdminClient().realm(REALM_NAME), "login-test");
    UserSessionRepresentation userSession = user.getUserSessions().get(0);
    getAdminClient().realm(REALM_NAME).deleteSession(userSession.getId());
    // Just one session expired.
    assertStatisticsExpected("After logout single session", InfinispanConnectionProvider.USER_SESSION_CACHE_NAME, InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME, cacheDc1Statistics, cacheDc2Statistics, channelStatisticsCrossDc, sessions01 + SESSIONS_COUNT - 1, sessions02 + SESSIONS_COUNT - 1, clientSessions01 + SESSIONS_COUNT - 1, clientSessions02 + SESSIONS_COUNT - 1, remoteSessions01 + SESSIONS_COUNT - 1, remoteSessions02 + SESSIONS_COUNT - 1, true);
    // Logout all sessions for user now
    user.logout();
    // Assert sessions removed on node1 and node2 and on remote caches.
    assertStatisticsExpected("After user logout", InfinispanConnectionProvider.USER_SESSION_CACHE_NAME, InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME, cacheDc1Statistics, cacheDc2Statistics, channelStatisticsCrossDc, sessions01, sessions02, clientSessions01, clientSessions02, remoteSessions01, remoteSessions02, true);
}
Also used : UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) UserResource(org.keycloak.admin.client.resource.UserResource) Test(org.junit.Test)

Example 13 with UserSessionRepresentation

use of org.keycloak.representations.idm.UserSessionRepresentation in project keycloak by keycloak.

the class AuthzClientCredentialsTest method testSingleSessionPerUser.

@Test
public void testSingleSessionPerUser() throws Exception {
    ClientsResource clients = getAdminClient().realm("authz-test-session").clients();
    ClientRepresentation clientRepresentation = clients.findByClientId("resource-server-test").get(0);
    List<UserSessionRepresentation> userSessions = clients.get(clientRepresentation.getId()).getUserSessions(-1, -1);
    assertEquals(0, userSessions.size());
    AuthzClient authzClient = getAuthzClient("default-session-keycloak.json");
    org.keycloak.authorization.client.resource.AuthorizationResource authorization = authzClient.authorization("marta", "password");
    AuthorizationResponse response = authorization.authorize();
    AccessToken accessToken = toAccessToken(response.getToken());
    String sessionState = accessToken.getSessionState();
    assertEquals(1, accessToken.getAuthorization().getPermissions().size());
    assertEquals("Default Resource", accessToken.getAuthorization().getPermissions().iterator().next().getResourceName());
    userSessions = clients.get(clientRepresentation.getId()).getUserSessions(null, null);
    assertEquals(1, userSessions.size());
    for (int i = 0; i < 3; i++) {
        response = authorization.authorize();
        accessToken = toAccessToken(response.getToken());
        assertEquals(sessionState, accessToken.getSessionState());
        Thread.sleep(1000);
    }
    userSessions = clients.get(clientRepresentation.getId()).getUserSessions(null, null);
    assertEquals(1, userSessions.size());
}
Also used : UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) AuthzClient(org.keycloak.authorization.client.AuthzClient) AccessToken(org.keycloak.representations.AccessToken) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) Test(org.junit.Test)

Example 14 with UserSessionRepresentation

use of org.keycloak.representations.idm.UserSessionRepresentation in project keycloak by keycloak.

the class BrokerTest method testNoNameIDAndPrincipalFromAttribute.

@Test
public void testNoNameIDAndPrincipalFromAttribute() throws IOException {
    final String userName = "newUser-" + UUID.randomUUID();
    final RealmResource realm = adminClient.realm(REALM_NAME);
    final IdentityProviderRepresentation rep = addIdentityProvider("https://saml.idp/");
    rep.getConfig().put(SAMLIdentityProviderConfig.NAME_ID_POLICY_FORMAT, "undefined");
    rep.getConfig().put(SAMLIdentityProviderConfig.PRINCIPAL_TYPE, SamlPrincipalType.ATTRIBUTE.toString());
    rep.getConfig().put(SAMLIdentityProviderConfig.PRINCIPAL_ATTRIBUTE, "user");
    try (IdentityProviderCreator idp = new IdentityProviderCreator(realm, rep)) {
        new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, POST).build().login().idp(SAML_BROKER_ALIAS).build().processSamlResponse(REDIRECT).transformObject(this::createAuthnResponse).transformObject(resp -> {
            final ResponseType rt = (ResponseType) resp;
            final AssertionType assertion = rt.getAssertions().get(0).getAssertion();
            // Remove NameID from subject
            assertion.getSubject().setSubType(null);
            // Add attribute to get principal from
            AttributeStatementType attrStatement = new AttributeStatementType();
            AttributeType attribute = new AttributeType("user");
            attribute.addAttributeValue(userName);
            attrStatement.addAttribute(new ASTChoiceType(attribute));
            rt.getAssertions().get(0).getAssertion().addStatement(attrStatement);
            return rt;
        }).targetAttributeSamlResponse().targetUri(getSamlBrokerUrl(REALM_NAME)).build().followOneRedirect().updateProfile().username(userName).firstName("someFirstName").lastName("someLastName").email("some@email.com").build().followOneRedirect().assertResponse(org.keycloak.testsuite.util.Matchers.statusCodeIsHC(200)).execute();
    }
    final UserRepresentation userRepresentation = realm.users().search(userName).stream().findFirst().get();
    final List<UserSessionRepresentation> userSessions = realm.users().get(userRepresentation.getId()).getUserSessions();
    assertThat(userSessions, hasSize(1));
}
Also used : XMLTimeUtil(org.keycloak.saml.processing.core.saml.v2.util.XMLTimeUtil) KeyPair(java.security.KeyPair) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) POST(org.keycloak.testsuite.util.SamlClient.Binding.POST) Header(org.apache.http.Header) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) SAML2Object(org.keycloak.dom.saml.v2.SAML2Object) SAMLIdentityProviderConfig(org.keycloak.broker.saml.SAMLIdentityProviderConfig) SAMLIdentityProviderFactory(org.keycloak.broker.saml.SAMLIdentityProviderFactory) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) ConditionsType(org.keycloak.dom.saml.v2.assertion.ConditionsType) Document(org.w3c.dom.Document) Requirement(org.keycloak.models.AuthenticationExecutionModel.Requirement) NameIDPolicyType(org.keycloak.dom.saml.v2.protocol.NameIDPolicyType) HasQName(org.keycloak.saml.processing.core.parsers.util.HasQName) URI(java.net.URI) HttpHeaders(org.apache.http.HttpHeaders) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) RealmResource(org.keycloak.admin.client.resource.RealmResource) IdentityProviderBuilder(org.keycloak.testsuite.util.IdentityProviderBuilder) UUID(java.util.UUID) Objects(java.util.Objects) List(java.util.List) Matchers.isSamlStatusResponse(org.keycloak.testsuite.util.Matchers.isSamlStatusResponse) Matchers.is(org.hamcrest.Matchers.is) SAML_CLIENT_ID_SALES_POST(org.keycloak.testsuite.saml.AbstractSamlTest.SAML_CLIENT_ID_SALES_POST) QName(javax.xml.namespace.QName) SamlPrincipalType(org.keycloak.protocol.saml.SamlPrincipalType) XmlDSigQNames(org.keycloak.saml.processing.core.parsers.saml.xmldsig.XmlDSigQNames) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) AtomicReference(java.util.concurrent.atomic.AtomicReference) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AuthenticationExecutionInfoRepresentation(org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation) RSA_SHA1(org.keycloak.saml.SignatureAlgorithm.RSA_SHA1) REDIRECT(org.keycloak.testsuite.util.SamlClient.Binding.REDIRECT) SAML2LoginResponseBuilder(org.keycloak.saml.SAML2LoginResponseBuilder) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) DOMException(org.w3c.dom.DOMException) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) UserResource(org.keycloak.admin.client.resource.UserResource) Status(javax.ws.rs.core.Response.Status) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) NodeList(org.w3c.dom.NodeList) AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) REALM_NAME(org.keycloak.testsuite.saml.AbstractSamlTest.REALM_NAME) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) SAML_ASSERTION_CONSUMER_URL_SALES_POST(org.keycloak.testsuite.saml.AbstractSamlTest.SAML_ASSERTION_CONSUMER_URL_SALES_POST) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) IdentityProviderCreator(org.keycloak.testsuite.updaters.IdentityProviderCreator) IdpReviewProfileAuthenticatorFactory(org.keycloak.authentication.authenticators.broker.IdpReviewProfileAuthenticatorFactory) BaseSAML2BindingBuilder(org.keycloak.saml.BaseSAML2BindingBuilder) Element(org.w3c.dom.Element) Assert(org.junit.Assert) UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) IdentityProviderCreator(org.keycloak.testsuite.updaters.IdentityProviderCreator) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Test(org.junit.Test)

Example 15 with UserSessionRepresentation

use of org.keycloak.representations.idm.UserSessionRepresentation in project keycloak by keycloak.

the class IdpInitiatedLoginTest method testTwoConsequentIdpInitiatedLogins.

@Test
public void testTwoConsequentIdpInitiatedLogins() {
    new SamlClientBuilder().idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build().login().user(bburkeUser).build().processSamlResponse(Binding.POST).transformObject(ob -> {
        assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
        ResponseType resp = (ResponseType) ob;
        assertThat(resp.getDestination(), is(SAML_ASSERTION_CONSUMER_URL_SALES_POST));
        return null;
    }).build().idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post2").build().login().sso(true).build().processSamlResponse(Binding.POST).transformObject(ob -> {
        assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
        ResponseType resp = (ResponseType) ob;
        assertThat(resp.getDestination(), is(SAML_ASSERTION_CONSUMER_URL_SALES_POST2));
        return null;
    }).build().execute();
    final UsersResource users = adminClient.realm(REALM_NAME).users();
    final ClientsResource clients = adminClient.realm(REALM_NAME).clients();
    UserRepresentation bburkeUserRepresentation = users.search(bburkeUser.getUsername()).stream().findFirst().get();
    List<UserSessionRepresentation> userSessions = users.get(bburkeUserRepresentation.getId()).getUserSessions();
    assertThat(userSessions, hasSize(1));
    Map<String, String> clientSessions = userSessions.get(0).getClients();
    Set<String> clientIds = clientSessions.values().stream().flatMap(c -> clients.findByClientId(c).stream()).map(ClientRepresentation::getClientId).collect(Collectors.toSet());
    assertThat(clientIds, containsInAnyOrder(SAML_CLIENT_ID_SALES_POST, SAML_CLIENT_ID_SALES_POST2));
}
Also used : UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) UsersResource(org.keycloak.admin.client.resource.UsersResource) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) Matchers.containsString(org.hamcrest.Matchers.containsString) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Test(org.junit.Test)

Aggregations

UserSessionRepresentation (org.keycloak.representations.idm.UserSessionRepresentation)16 Test (org.junit.Test)11 ClientsResource (org.keycloak.admin.client.resource.ClientsResource)6 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)6 UserResource (org.keycloak.admin.client.resource.UserResource)4 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)4 Map (java.util.Map)3 AuthzClient (org.keycloak.authorization.client.AuthzClient)3 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)3 URI (java.net.URI)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Objects (java.util.Objects)2 Response (javax.ws.rs.core.Response)2 RealmResource (org.keycloak.admin.client.resource.RealmResource)2 UsersResource (org.keycloak.admin.client.resource.UsersResource)2 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)2 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)2 OAuthClient (org.keycloak.testsuite.util.OAuthClient)2 AccessTokenResponse (org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse)2