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());
}
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);
}
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());
}
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));
}
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));
}
Aggregations