Search in sources :

Example 1 with UserSessionRepresentation

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

the class UserResource method toUserSessionRepresentation.

/**
 * Converts the specified {@link UserSessionModel} into a {@link UserSessionRepresentation}.
 *
 * @param userSession the model to be converted.
 * @param clientUuid the client's UUID.
 * @return a reference to the constructed representation or {@code null} if the session is not associated with the specified
 * client.
 */
private UserSessionRepresentation toUserSessionRepresentation(final UserSessionModel userSession, final String clientUuid) {
    UserSessionRepresentation rep = ModelToRepresentation.toRepresentation(userSession);
    // Update lastSessionRefresh with the timestamp from clientSession
    AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(clientUuid);
    if (clientSession == null) {
        return null;
    }
    rep.setLastAccess(Time.toMillis(clientSession.getTimestamp()));
    return rep;
}
Also used : UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel)

Example 2 with UserSessionRepresentation

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

the class UserResource method getOfflineSessions.

/**
 * Get offline sessions associated with the user and client
 *
 * @return
 */
@Path("offline-sessions/{clientUuid}")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Stream<UserSessionRepresentation> getOfflineSessions(@PathParam("clientUuid") final String clientUuid) {
    auth.users().requireView(user);
    ClientModel client = realm.getClientById(clientUuid);
    if (client == null) {
        throw new NotFoundException("Client not found");
    }
    return new UserSessionManager(session).findOfflineSessionsStream(realm, user).map(session -> toUserSessionRepresentation(session, clientUuid)).filter(Objects::nonNull);
}
Also used : UserSessionManager(org.keycloak.services.managers.UserSessionManager) EmailTemplateProvider(org.keycloak.email.EmailTemplateProvider) RedirectUtils(org.keycloak.protocol.oidc.utils.RedirectUtils) Produces(javax.ws.rs.Produces) USER_API(org.keycloak.userprofile.UserProfileContext.USER_API) MediaType(javax.ws.rs.core.MediaType) ErrorResponseException(org.keycloak.services.ErrorResponseException) Validation(org.keycloak.services.validation.Validation) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) UserConsentRepresentation(org.keycloak.representations.idm.UserConsentRepresentation) UriBuilder(javax.ws.rs.core.UriBuilder) Time(org.keycloak.common.util.Time) UserCredentialModel(org.keycloak.models.UserCredentialModel) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Set(java.util.Set) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) Stream(java.util.stream.Stream) LoginActionsService(org.keycloak.services.resources.LoginActionsService) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) WebApplicationException(javax.ws.rs.WebApplicationException) GET(javax.ws.rs.GET) Constants(org.keycloak.models.Constants) ArrayList(java.util.ArrayList) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) UserModel(org.keycloak.models.UserModel) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) UserConsentManager(org.keycloak.services.managers.UserConsentManager) ProviderFactory(org.keycloak.provider.ProviderFactory) UserManager(org.keycloak.models.UserManager) Properties(java.util.Properties) CredentialModel(org.keycloak.credential.CredentialModel) ExecuteActionsActionToken(org.keycloak.authentication.actiontoken.execactions.ExecuteActionsActionToken) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) EventType(org.keycloak.events.EventType) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) IMPERSONATOR_USERNAME(org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_USERNAME) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ValidationException(org.keycloak.userprofile.ValidationException) ResourceType(org.keycloak.events.admin.ResourceType) Path(javax.ws.rs.Path) GroupRepresentation(org.keycloak.representations.idm.GroupRepresentation) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) QueryParam(javax.ws.rs.QueryParam) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) Consumes(javax.ws.rs.Consumes) ReadOnlyException(org.keycloak.storage.ReadOnlyException) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) DefaultValue(javax.ws.rs.DefaultValue) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) BadRequestException(javax.ws.rs.BadRequestException) URI(java.net.URI) AccountFormService(org.keycloak.services.resources.account.AccountFormService) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) IMPERSONATOR_ID(org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_ID) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ForbiddenException(org.keycloak.services.ForbiddenException) ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) UserProfile(org.keycloak.userprofile.UserProfile) PathParam(javax.ws.rs.PathParam) UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) Profile(org.keycloak.common.Profile) Logger(org.jboss.logging.Logger) HashMap(java.util.HashMap) ServicesLogger(org.keycloak.services.ServicesLogger) ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) MessageFormat(java.text.MessageFormat) HashSet(java.util.HashSet) EventBuilder(org.keycloak.events.EventBuilder) UserConsentModel(org.keycloak.models.UserConsentModel) EmailException(org.keycloak.email.EmailException) GroupModel(org.keycloak.models.GroupModel) LinkedList(java.util.LinkedList) ProfileHelper(org.keycloak.utils.ProfileHelper) Status(javax.ws.rs.core.Response.Status) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) POST(javax.ws.rs.POST) UserLoginFailureModel(org.keycloak.models.UserLoginFailureModel) UserSessionModel(org.keycloak.models.UserSessionModel) TimeUnit(java.util.concurrent.TimeUnit) NoCache(org.jboss.resteasy.annotations.cache.NoCache) UserSessionManager(org.keycloak.services.managers.UserSessionManager) ModelException(org.keycloak.models.ModelException) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) ErrorResponse(org.keycloak.services.ErrorResponse) ClientModel(org.keycloak.models.ClientModel) Objects(java.util.Objects) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 3 with UserSessionRepresentation

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

the class KcSamlIdPInitiatedSsoTest method assertSingleUserSession.

private void assertSingleUserSession(String realmName, String userName, String... expectedClientIds) {
    final UsersResource users = adminClient.realm(realmName).users();
    final ClientsResource clients = adminClient.realm(realmName).clients();
    UserRepresentation userRepresentation = users.search(userName).stream().findFirst().get();
    List<UserSessionRepresentation> userSessions = users.get(userRepresentation.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(expectedClientIds));
}
Also used : UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) UsersResource(org.keycloak.admin.client.resource.UsersResource) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) Matchers.containsString(org.hamcrest.Matchers.containsString) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 4 with UserSessionRepresentation

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

the class ClientTest method getClientSessions.

@Test
public void getClientSessions() throws Exception {
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
    assertEquals(200, response.getStatusCode());
    OAuthClient.AuthorizationEndpointResponse codeResponse = oauth.doLogin("test-user@localhost", "password");
    OAuthClient.AccessTokenResponse response2 = oauth.doAccessTokenRequest(codeResponse.getCode(), "password");
    assertEquals(200, response2.getStatusCode());
    ClientResource app = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    assertEquals(2, (long) app.getApplicationSessionCount().get("count"));
    List<UserSessionRepresentation> userSessions = app.getUserSessions(0, 100);
    assertEquals(2, userSessions.size());
    assertEquals(1, userSessions.get(0).getClients().size());
}
Also used : UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessTokenResponse(org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse) ClientResource(org.keycloak.admin.client.resource.ClientResource) Test(org.junit.Test)

Example 5 with UserSessionRepresentation

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

the class AppInitiatedActionResetPasswordTest method checkLogoutSessions.

@Test
public void checkLogoutSessions() {
    OAuthClient oauth2 = new OAuthClient();
    oauth2.init(driver2);
    loginPage.open();
    loginPage.login("test-user@localhost", "password");
    events.expectLogin().assertEvent();
    UserResource testUser = testRealm().users().get(findUser("test-user@localhost").getId());
    List<UserSessionRepresentation> sessions = testUser.getUserSessions();
    assertEquals(1, sessions.size());
    final String firstSessionId = sessions.get(0).getId();
    oauth2.doLogin("test-user@localhost", "password");
    events.expectLogin().assertEvent();
    assertEquals(2, testUser.getUserSessions().size());
    doAIA();
    changePasswordPage.assertCurrent();
    assertTrue("Logout sessions is checked by default", changePasswordPage.isLogoutSessionsChecked());
    changePasswordPage.changePassword("All Right Then, Keep Your Secrets", "All Right Then, Keep Your Secrets");
    events.expectRequiredAction(EventType.UPDATE_PASSWORD).assertEvent();
    assertKcActionStatus(SUCCESS);
    sessions = testUser.getUserSessions();
    assertEquals(1, sessions.size());
    assertEquals("Old session is still valid", firstSessionId, sessions.get(0).getId());
}
Also used : UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) OAuthClient(org.keycloak.testsuite.util.OAuthClient) UserResource(org.keycloak.admin.client.resource.UserResource) 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