From d3d1021d32a2962d0cc7a667590f15d52231a1d0 Mon Sep 17 00:00:00 2001 From: Muhammed Oguz Date: Fri, 10 Apr 2026 00:30:45 +0300 Subject: [PATCH 1/8] Add per-application session termination to Account Console Allow users to end their active sessions with an individual application from the Applications page. Applications with an active session show an "End application session" action, backed by a new account REST API endpoint DELETE /applications/{clientId}/sessions. The endpoint detaches the client sessions from the user's online sessions, notifying the client via backchannel logout when supported, and removes user sessions that no longer have any client sessions. Offline sessions are not affected. The Account Console itself does not offer the action for its own client. Closes #47921 Signed-off-by: Muhammed Oguz --- .../server_admin/topics/account.adoc | 15 +++ .../account/messages/messages_tr.properties | 4 + .../account/messages/messages_en.properties | 4 + js/apps/account-ui/src/api/methods.ts | 9 ++ .../src/applications/Applications.tsx | 49 +++++++- js/apps/account-ui/test/applications.spec.ts | 88 ++++++++++++++ .../resources/account/AccountRestService.java | 45 +++++++ .../tests/account/AccountRestServiceTest.java | 111 ++++++++++++++++++ 8 files changed, 324 insertions(+), 1 deletion(-) diff --git a/docs/documentation/server_admin/topics/account.adoc b/docs/documentation/server_admin/topics/account.adoc index bac67c644ca..5b886ee940e 100644 --- a/docs/documentation/server_admin/topics/account.adoc +++ b/docs/documentation/server_admin/topics/account.adoc @@ -125,6 +125,21 @@ The *Applications* menu item shows users which applications you can access. In t image:images/account-console-applications.png[Applications] +==== Ending an application session + +You can end your active sessions with a specific application directly from the *Applications* page. Applications that have an active session are marked as *In use* and display an *End application session* button. The Account Console itself does not display this button. + +.Procedure + +. Click *Applications* in the menu. +. Find the application whose session you want to end. +. Click *End application session* next to the application. +. Click *Confirm* in the confirmation dialog. + +The sessions of the application for your account are ended. If the application supports it, {project_name} also notifies the application about the logout. Note that if your account still has an active session, for example because other applications are using it, the application might sign you in again automatically without asking for your credentials. To fully sign out from all applications, use the *Sign out* action on the *Device activity* page instead. + +Ending an application session does not revoke previously granted offline access. To revoke offline access, use the *Remove access* action for the application. + === Viewing group memberships You can view the groups you are associated with by clicking the *Groups* menu. diff --git a/js/apps/account-ui/maven-resources-community/theme/keycloak.v3/account/messages/messages_tr.properties b/js/apps/account-ui/maven-resources-community/theme/keycloak.v3/account/messages/messages_tr.properties index ace71c463b0..79eea92143f 100644 --- a/js/apps/account-ui/maven-resources-community/theme/keycloak.v3/account/messages/messages_tr.properties +++ b/js/apps/account-ui/maven-resources-community/theme/keycloak.v3/account/messages/messages_tr.properties @@ -52,6 +52,10 @@ close=Kapat email=Email signOutWarning=Oturumu sonlandıralım mı? removeConsentError=Şu nedenlerle onay kaldırılamadı: {{error}} +endApplicationSession=Uygulama oturumunu sonlandır +endApplicationSessionSuccess={{name}} için uygulama oturumu sonlandırıldı +endApplicationSessionError=Şu nedenle uygulama oturumu sonlandırılamadı\: {{error}} +endApplicationSessionMessage=Bu işlem {{name}} ile olan aktif oturumlarınızı sonlandırır. Hesap oturumunuz hâlâ aktifse, uygulama kimlik bilgileriniz sorulmadan sizi otomatik olarak yeniden oturum açtırabilir. signOutAllDevicesWarning=Bu eylem, kullandığınız mevcut cihaz da dahil olmak üzere hesabınızda oturum açmış olan tüm cihazların oturumunu kapatacaktır. unShareSuccess=Kaynak başarıyla paylaşımdan kaldırıldı. signingIn=Oturum açma diff --git a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties index 882986fb458..ddfb08c43bb 100644 --- a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties +++ b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties @@ -55,6 +55,10 @@ close=Close email=Email signOutWarning=Sign out the session? removeConsentError=Could not remove consent due to\: {{error}} +endApplicationSession=End application session +endApplicationSessionSuccess=Ended the application session for {{name}} +endApplicationSessionError=Could not end the application session due to\: {{error}} +endApplicationSessionMessage=This ends your active sessions with {{name}}. If your account session is still active, the application might sign you in again automatically without asking for credentials. signOutAllDevicesWarning=This action will sign out all the devices that have signed in to your account, including the current device you are using. unShareSuccess=Resource successfully un-shared. signingIn=Signing in diff --git a/js/apps/account-ui/src/api/methods.ts b/js/apps/account-ui/src/api/methods.ts index 99d07957b57..226adea07be 100644 --- a/js/apps/account-ui/src/api/methods.ts +++ b/js/apps/account-ui/src/api/methods.ts @@ -105,6 +105,15 @@ export async function deleteSession( }); } +export async function deleteApplicationSessions( + context: KeycloakContext, + clientId: string, +) { + return request(`/applications/${clientId}/sessions`, context, { + method: "DELETE", + }); +} + export async function getCredentials({ signal, context }: CallOptions) { const response = await request("/credentials", context, { signal, diff --git a/js/apps/account-ui/src/applications/Applications.tsx b/js/apps/account-ui/src/applications/Applications.tsx index 1479bdfbc48..fb75851d521 100644 --- a/js/apps/account-ui/src/applications/Applications.tsx +++ b/js/apps/account-ui/src/applications/Applications.tsx @@ -29,7 +29,11 @@ import { useState } from "react"; import { useTranslation } from "react-i18next"; import { AccountEnvironment } from ".."; -import { deleteConsent, getApplications } from "../api/methods"; +import { + deleteApplicationSessions, + deleteConsent, + getApplications, +} from "../api/methods"; import { ClientRepresentation } from "../api/representations"; import { Page } from "../components/page/Page"; import type { TFuncKey } from "../i18n-type"; @@ -84,6 +88,16 @@ export const Applications = () => { } }; + const endApplicationSession = async (id: string, name: string) => { + try { + await deleteApplicationSessions(context, id); + refresh(); + addAlert(t("endApplicationSessionSuccess", { name })); + } catch (error) { + addError("endApplicationSessionError", error); + } + }; + if (!applications) { return ; } @@ -125,6 +139,11 @@ export const Applications = () => { > {t("status")} , + , ]} /> @@ -182,6 +201,34 @@ export const Applications = () => { {application.inUse ? t("inUse") : t("notInUse")} , + + {application.inUse && + application.clientId !== context.environment.clientId && ( + + endApplicationSession( + application.clientId, + label( + t, + application.clientName || application.clientId, + ), + ) + } + > + {t("endApplicationSessionMessage", { + name: label( + t, + application.clientName || application.clientId, + ), + })} + + )} + , ]} /> diff --git a/js/apps/account-ui/test/applications.spec.ts b/js/apps/account-ui/test/applications.spec.ts index f3078fb50ee..4313da019b4 100644 --- a/js/apps/account-ui/test/applications.spec.ts +++ b/js/apps/account-ui/test/applications.spec.ts @@ -53,4 +53,92 @@ test.describe("Applications", () => { await expect(applications.nth(1)).toContainText("Beta Application"); await expect(applications.nth(2)).toContainText("Zebra Application"); }); + + test("ends the session of an application", async ({ page }) => { + await using testBed = await createTestBed(); + + // Mock an application with an active session, the backend behavior is covered by AccountRestServiceTest. + await page.route("**/applications", async (route) => { + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify([ + { + clientId: "my-application", + clientName: "My Application", + inUse: true, + }, + ]), + }); + }); + + let sessionsDeleted = false; + await page.route( + "**/applications/my-application/sessions", + async (route) => { + expect(route.request().method()).toBe("DELETE"); + sessionsDeleted = true; + await route.fulfill({ status: 204 }); + }, + ); + + // Log in and navigate to the applications page. + await login(page, testBed.realm); + await page.getByTestId("applications").click(); + + // The application has an active session, so the action is shown. + const endSessionButton = page.getByRole("button", { + name: "End application session", + exact: true, + }); + await expect(endSessionButton).toBeVisible(); + + // Click the action and confirm the modal. + await endSessionButton.click(); + await page.getByRole("button", { name: "Confirm", exact: true }).click(); + + // Expect a success alert after the sessions have been deleted. + await expect(page.getByTestId("last-alert")).toContainText( + "Ended the application session for My Application", + ); + expect(sessionsDeleted).toBe(true); + }); + + test("does not show the end session action for applications without an active session or for the Account Console itself", async ({ + page, + }) => { + await using testBed = await createTestBed(); + + await page.route("**/applications", async (route) => { + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify([ + { + clientId: "account-console", + clientName: "Account Console", + inUse: true, + }, + { + clientId: "other-application", + clientName: "Other Application", + inUse: false, + }, + ]), + }); + }); + + // Log in and navigate to the applications page. + await login(page, testBed.realm); + await page.getByTestId("applications").click(); + + // Neither the Account Console itself nor an application without an active session shows the action. + await expect(page.getByTestId("applications-list-item")).toHaveCount(2); + await expect( + page.getByRole("button", { + name: "End application session", + exact: true, + }), + ).toHaveCount(0); + }); }); diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java index 5e8493dd535..357817e8696 100755 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java @@ -71,6 +71,7 @@ import org.keycloak.representations.idm.GroupRepresentation; import org.keycloak.services.ErrorResponse; import org.keycloak.services.managers.Auth; +import org.keycloak.services.managers.AuthenticationManager; import org.keycloak.services.managers.UserConsentManager; import org.keycloak.services.messages.Messages; import org.keycloak.services.resources.account.resources.ResourcesService; @@ -391,6 +392,50 @@ public Response revokeConsent(final @PathParam("clientId") String clientId) { return Response.noContent().build(); } + /** + * Ends all active online sessions of the user for the client with the given client id. + * The client sessions are detached from the user sessions, and the client is notified + * via backchannel logout when supported. A user session that no longer has any client + * sessions afterwards is removed. Offline sessions are not affected. + * + * @param clientId client id to end the sessions for + * @return returns 204 if the sessions were ended + */ + @Path("/applications/{clientId}/sessions") + @DELETE + @NoCache + public Response revokeApplicationSessions(final @PathParam("clientId") String clientId) { + checkAccountApiEnabled(); + auth.require(AccountRoles.MANAGE_ACCOUNT); + + event.event(EventType.LOGOUT); + ClientModel client = realm.getClientByClientId(clientId); + if (client == null) { + String msg = String.format("No client with clientId: %s found.", clientId); + event.error(msg); + throw ErrorResponse.error(msg, Response.Status.NOT_FOUND); + } + + session.sessions().getUserSessionsStream(realm, user) + .filter(userSession -> userSession.getAuthenticatedClientSessionByClient(client.getId()) != null) + .toList() // collect to avoid concurrent modification. + .forEach(userSession -> { + AuthenticationManager.backchannelLogoutUserSessionFromClient(session, realm, userSession, client, + session.getContext().getUri(), headers); + if (userSession.getAuthenticatedClientSessions().isEmpty()) { + // The last client session was ended, remove the now empty user session as well. + session.sessions().removeUserSession(realm, userSession); + } + event.clone() + .event(EventType.LOGOUT) + .detail(Details.REVOKED_CLIENT, client.getClientId()) + .session(userSession) + .success(); + }); + + return Response.noContent().build(); + } + /** * Creates or updates the consent of the given, requested consent for * the client with the given client id. Returns the appropriate REST response. diff --git a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java index 6f4b4d7da35..0b32600513f 100644 --- a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java @@ -1282,6 +1282,117 @@ public void listApplicationsOfflineAccess() throws Exception { assertClientRep(apps.get("offline-client-without-base-url"), "Offline Client Without Base URL", null, false, false, true, null, null); } + @Test + public void revokeApplicationSessions() throws Exception { + managedRealm.cleanup().add(RealmResource::logoutAll); + + // Create a session for "in-use-client" via direct grant + oauth.client("in-use-client", "secret1"); + AccessTokenResponse tokenResponse = oauth.doPasswordGrantRequest("manage-account-access", "password"); + Assertions.assertNull(tokenResponse.getErrorDescription()); + + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("manage-account-access", "password").getAccessToken(); + + // skip the two direct access grant logins + events.skip(2); + + UserResource user = AdminApiUtil.findUserByUsernameId(managedRealm.admin(), "manage-account-access"); + Assertions.assertEquals(2, user.getUserSessions().size()); + + // Verify the client is "in use" + List applications = simpleHttp + .doGet(getAccountUrl("applications")) + .header("Accept", "application/json") + .auth(token) + .asJson(new TypeReference>() { + }); + Map apps = applications.stream().collect(Collectors.toMap(x -> x.getClientId(), x -> x)); + Assertions.assertTrue(apps.get("in-use-client").isInUse()); + + // End the application sessions + try (SimpleHttpResponse response = simpleHttp + .doDelete(getAccountUrl("applications/in-use-client/sessions")) + .header("Accept", "application/json") + .auth(token) + .asResponse()) { + Assertions.assertEquals(204, response.getStatus()); + } + + // A logout event is fired for the session of "in-use-client" + EventAssertion.assertSuccess(events.poll()) + .type(EventType.LOGOUT) + .clientId("account") + .userId(user.toRepresentation().getId()) + .sessionId(tokenResponse.getSessionState()) + .details(Details.REVOKED_CLIENT, "in-use-client"); + Assertions.assertNull(events.poll()); + + // The user session of "in-use-client" had no other client sessions and was removed as well + List userSessions = user.getUserSessions(); + Assertions.assertEquals(1, userSessions.size()); + Assertions.assertNotEquals(tokenResponse.getSessionState(), userSessions.get(0).getId()); + + // Verify the client is no longer "in use" + applications = simpleHttp + .doGet(getAccountUrl("applications")) + .header("Accept", "application/json") + .auth(token) + .asJson(new TypeReference>() { + }); + apps = applications.stream().collect(Collectors.toMap(x -> x.getClientId(), x -> x)); + Assertions.assertFalse(apps.containsKey("in-use-client") && apps.get("in-use-client").isInUse()); + } + + @Test + public void revokeApplicationSessionsForNotExistingClient() throws IOException { + managedRealm.cleanup().add(RealmResource::logoutAll); + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("manage-account-access", "password").getAccessToken(); + try (SimpleHttpResponse response = simpleHttp + .doDelete(getAccountUrl("applications/not-existing/sessions")) + .header("Accept", "application/json") + .auth(token) + .asResponse()) { + Assertions.assertEquals(404, response.getStatus()); + } + } + + @Test + public void revokeApplicationSessionsWithoutPermission() throws IOException { + managedRealm.cleanup().add(RealmResource::logoutAll); + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("view-account-access", "password").getAccessToken(); + try (SimpleHttpResponse response = simpleHttp + .doDelete(getAccountUrl("applications/in-use-client/sessions")) + .header("Accept", "application/json") + .auth(token) + .asResponse()) { + Assertions.assertEquals(403, response.getStatus()); + } + } + + @Test + public void revokeApplicationSessionsIdempotent() throws IOException { + managedRealm.cleanup().add(RealmResource::logoutAll); + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("manage-account-access", "password").getAccessToken(); + + // Delete sessions when there are none -- should still return 204 + try (SimpleHttpResponse response = simpleHttp + .doDelete(getAccountUrl("applications/in-use-client/sessions")) + .header("Accept", "application/json") + .auth(token) + .asResponse()) { + Assertions.assertEquals(204, response.getStatus()); + } + + // Call again -- still 204 + try (SimpleHttpResponse response = simpleHttp + .doDelete(getAccountUrl("applications/in-use-client/sessions")) + .header("Accept", "application/json") + .auth(token) + .asResponse()) { + Assertions.assertEquals(204, response.getStatus()); + } + } + @Test public void listApplicationsThirdPartyWithoutConsentText() throws Exception { listApplicationsThirdParty("acr", false); From 76fd7ecf29a8f55d3417da303a63549d5e8ac5a1 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Mon, 10 Aug 2026 17:12:46 +0900 Subject: [PATCH 2/8] Review: Allow removal of offline sessions, defer Turkish translation Signed-off-by: Alexander Schwartz --- .../keycloak.v3/account/messages/messages_tr.properties | 4 ---- js/apps/account-ui/src/applications/Applications.tsx | 6 ++++-- .../services/resources/account/AccountRestService.java | 4 ++-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/js/apps/account-ui/maven-resources-community/theme/keycloak.v3/account/messages/messages_tr.properties b/js/apps/account-ui/maven-resources-community/theme/keycloak.v3/account/messages/messages_tr.properties index 79eea92143f..ace71c463b0 100644 --- a/js/apps/account-ui/maven-resources-community/theme/keycloak.v3/account/messages/messages_tr.properties +++ b/js/apps/account-ui/maven-resources-community/theme/keycloak.v3/account/messages/messages_tr.properties @@ -52,10 +52,6 @@ close=Kapat email=Email signOutWarning=Oturumu sonlandıralım mı? removeConsentError=Şu nedenlerle onay kaldırılamadı: {{error}} -endApplicationSession=Uygulama oturumunu sonlandır -endApplicationSessionSuccess={{name}} için uygulama oturumu sonlandırıldı -endApplicationSessionError=Şu nedenle uygulama oturumu sonlandırılamadı\: {{error}} -endApplicationSessionMessage=Bu işlem {{name}} ile olan aktif oturumlarınızı sonlandırır. Hesap oturumunuz hâlâ aktifse, uygulama kimlik bilgileriniz sorulmadan sizi otomatik olarak yeniden oturum açtırabilir. signOutAllDevicesWarning=Bu eylem, kullandığınız mevcut cihaz da dahil olmak üzere hesabınızda oturum açmış olan tüm cihazların oturumunu kapatacaktır. unShareSuccess=Kaynak başarıyla paylaşımdan kaldırıldı. signingIn=Oturum açma diff --git a/js/apps/account-ui/src/applications/Applications.tsx b/js/apps/account-ui/src/applications/Applications.tsx index fb75851d521..46eb771e8a6 100644 --- a/js/apps/account-ui/src/applications/Applications.tsx +++ b/js/apps/account-ui/src/applications/Applications.tsx @@ -199,10 +199,12 @@ export const Applications = () => { {application.offlineAccess ? ", " + t("offlineAccess") : ""} , - {application.inUse ? t("inUse") : t("notInUse")} + {application.inUse || application.offlineAccess + ? t("inUse") + : t("notInUse")} , - {application.inUse && + {(application.inUse || application.offlineAccess) && application.clientId !== context.environment.clientId && ( userSession.getAuthenticatedClientSessionByClient(client.getId()) != null) .toList() // collect to avoid concurrent modification. .forEach(userSession -> { From c82189d8d0a738d1bbaf2efe6bda0bac9f912f01 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Mon, 10 Aug 2026 17:33:17 +0900 Subject: [PATCH 3/8] Resolving GitHub Copilot comment Signed-off-by: Alexander Schwartz --- js/apps/account-ui/src/api/methods.ts | 10 +++++++--- .../services/resources/account/AccountRestService.java | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/js/apps/account-ui/src/api/methods.ts b/js/apps/account-ui/src/api/methods.ts index 226adea07be..08c5856e499 100644 --- a/js/apps/account-ui/src/api/methods.ts +++ b/js/apps/account-ui/src/api/methods.ts @@ -109,9 +109,13 @@ export async function deleteApplicationSessions( context: KeycloakContext, clientId: string, ) { - return request(`/applications/${clientId}/sessions`, context, { - method: "DELETE", - }); + return request( + `/applications/${encodeURIComponent(clientId)}/sessions`, + context, + { + method: "DELETE", + }, + ); } export async function getCredentials({ signal, context }: CallOptions) { diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java index 45ceb27f737..63423ad3861 100755 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java @@ -396,7 +396,7 @@ public Response revokeConsent(final @PathParam("clientId") String clientId) { * Ends all active online and offline sessions of the user for the client with the given client id. * The client sessions are detached from the user sessions, and the client is notified * via backchannel logout when supported. A user session that no longer has any client - * sessions afterwards is removed. Offline sessions are not affected. + * sessions afterward is removed. * * @param clientId client id to end the sessions for * @return returns 204 if the sessions were ended From 9bd053361af150c32bbcd7d50e55b3da55518457 Mon Sep 17 00:00:00 2001 From: Muhammed Oguz Date: Mon, 31 Aug 2026 18:34:27 +0300 Subject: [PATCH 4/8] Remove offline sessions when ending an application session Align offline session cleanup with online sessions: when the last client session of an offline user session is ended, remove the offline user session via removeOfflineUserSession instead of the online-only removeUserSession. Add API tests for offline and mixed online/offline revocation, a UI test for offline-only applications, and update the docs and confirmation message to reflect that offline sessions are ended. Signed-off-by: Muhammed Oguz --- .../server_admin/topics/account.adoc | 4 +- .../account/messages/messages_en.properties | 2 +- js/apps/account-ui/test/applications.spec.ts | 56 +++++++++ .../resources/account/AccountRestService.java | 6 +- .../tests/account/AccountRestServiceTest.java | 106 ++++++++++++++++++ 5 files changed, 170 insertions(+), 4 deletions(-) diff --git a/docs/documentation/server_admin/topics/account.adoc b/docs/documentation/server_admin/topics/account.adoc index 5b886ee940e..433ebff4245 100644 --- a/docs/documentation/server_admin/topics/account.adoc +++ b/docs/documentation/server_admin/topics/account.adoc @@ -136,9 +136,9 @@ You can end your active sessions with a specific application directly from the * . Click *End application session* next to the application. . Click *Confirm* in the confirmation dialog. -The sessions of the application for your account are ended. If the application supports it, {project_name} also notifies the application about the logout. Note that if your account still has an active session, for example because other applications are using it, the application might sign you in again automatically without asking for your credentials. To fully sign out from all applications, use the *Sign out* action on the *Device activity* page instead. +The sessions of the application for your account are ended, including any offline sessions, so the application can no longer use offline tokens to access {project_name} on your behalf. If the application supports it, {project_name} also notifies the application about the logout. Note that if your account still has an active session, for example because other applications are using it, the application might sign you in again automatically without asking for your credentials. To fully sign out from all applications, use the *Sign out* action on the *Device activity* page instead. -Ending an application session does not revoke previously granted offline access. To revoke offline access, use the *Remove access* action for the application. +Ending an application session does not revoke the access you granted to the application, so it can obtain new sessions the next time you use it. To revoke the granted access, use the *Remove access* action for the application. === Viewing group memberships diff --git a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties index ddfb08c43bb..b996b5ae75e 100644 --- a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties +++ b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties @@ -58,7 +58,7 @@ removeConsentError=Could not remove consent due to\: {{error}} endApplicationSession=End application session endApplicationSessionSuccess=Ended the application session for {{name}} endApplicationSessionError=Could not end the application session due to\: {{error}} -endApplicationSessionMessage=This ends your active sessions with {{name}}. If your account session is still active, the application might sign you in again automatically without asking for credentials. +endApplicationSessionMessage=This ends your active sessions with {{name}}, including offline sessions. If your account session is still active, the application might sign you in again automatically without asking for credentials. signOutAllDevicesWarning=This action will sign out all the devices that have signed in to your account, including the current device you are using. unShareSuccess=Resource successfully un-shared. signingIn=Signing in diff --git a/js/apps/account-ui/test/applications.spec.ts b/js/apps/account-ui/test/applications.spec.ts index 4313da019b4..4592d6f6f40 100644 --- a/js/apps/account-ui/test/applications.spec.ts +++ b/js/apps/account-ui/test/applications.spec.ts @@ -141,4 +141,60 @@ test.describe("Applications", () => { }), ).toHaveCount(0); }); + + test("shows the end session action for an application with only offline access", async ({ + page, + }) => { + await using testBed = await createTestBed(); + + // The application has no active online session, only offline access. + await page.route("**/applications", async (route) => { + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify([ + { + clientId: "offline-application", + clientName: "Offline Application", + inUse: false, + offlineAccess: true, + }, + ]), + }); + }); + + let sessionsDeleted = false; + await page.route( + "**/applications/offline-application/sessions", + async (route) => { + expect(route.request().method()).toBe("DELETE"); + sessionsDeleted = true; + await route.fulfill({ status: 204 }); + }, + ); + + // Log in and navigate to the applications page. + await login(page, testBed.realm); + await page.getByTestId("applications").click(); + + // Offline access counts as "in use" and exposes the action. + const listItem = page.getByTestId("applications-list-item"); + await expect(listItem).toContainText("In use"); + + const endSessionButton = page.getByRole("button", { + name: "End application session", + exact: true, + }); + await expect(endSessionButton).toBeVisible(); + + // Click the action and confirm the modal. + await endSessionButton.click(); + await page.getByRole("button", { name: "Confirm", exact: true }).click(); + + // Expect a success alert after the sessions have been deleted. + await expect(page.getByTestId("last-alert")).toContainText( + "Ended the application session for Offline Application", + ); + expect(sessionsDeleted).toBe(true); + }); }); diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java index 63423ad3861..8df47b5a3e8 100755 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java @@ -424,7 +424,11 @@ public Response revokeApplicationSessions(final @PathParam("clientId") String cl session.getContext().getUri(), headers); if (userSession.getAuthenticatedClientSessions().isEmpty()) { // The last client session was ended, remove the now empty user session as well. - session.sessions().removeUserSession(realm, userSession); + if (userSession.isOffline()) { + session.sessions().removeOfflineUserSession(realm, userSession); + } else { + session.sessions().removeUserSession(realm, userSession); + } } event.clone() .event(EventType.LOGOUT) diff --git a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java index 0b32600513f..5bce2369123 100644 --- a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java @@ -1393,6 +1393,102 @@ public void revokeApplicationSessionsIdempotent() throws IOException { } } + @Test + public void revokeApplicationSessionsOffline() throws Exception { + managedRealm.cleanup().add(RealmResource::logoutAll); + + // Create an offline session for "offline-client" + oauth.scope(OAuth2Constants.OFFLINE_ACCESS); + oauth.client("offline-client", "secret1"); + AccessTokenResponse offlineTokenResponse = oauth.doPasswordGrantRequest("manage-account-access", "password"); + Assertions.assertNull(offlineTokenResponse.getErrorDescription()); + String offlineRefreshToken = offlineTokenResponse.getRefreshToken(); + + // Get an account token via direct grant + oauth.scope(null); + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("manage-account-access", "password").getAccessToken(); + + // skip the offline_access login and the direct access grant login + events.skip(2); + + UserResource user = AdminApiUtil.findUserByUsernameId(managedRealm.admin(), "manage-account-access"); + + // The application is listed as having offline access + Map apps = getApplications(token); + Assertions.assertTrue(apps.get("offline-client").isOfflineAccess()); + + // End the application sessions + try (SimpleHttpResponse response = simpleHttp + .doDelete(getAccountUrl("applications/offline-client/sessions")) + .header("Accept", "application/json") + .auth(token) + .asResponse()) { + Assertions.assertEquals(204, response.getStatus()); + } + + // A logout event is fired for the offline session of "offline-client" + EventAssertion.assertSuccess(events.poll()) + .type(EventType.LOGOUT) + .clientId("account") + .userId(user.toRepresentation().getId()) + .sessionId(offlineTokenResponse.getSessionState()) + .details(Details.REVOKED_CLIENT, "offline-client"); + Assertions.assertNull(events.poll()); + + // The offline token can no longer be refreshed + oauth.client("offline-client", "secret1"); + AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(offlineRefreshToken); + Assertions.assertEquals("invalid_grant", refreshResponse.getError()); + + // The now empty offline user session was removed, so the application no longer reports offline access + apps = getApplications(token); + Assertions.assertFalse(apps.containsKey("offline-client") && apps.get("offline-client").isOfflineAccess()); + } + + @Test + public void revokeApplicationSessionsOnlineAndOffline() throws Exception { + managedRealm.cleanup().add(RealmResource::logoutAll); + + // Create an online session for "offline-client" + oauth.scope(null); + oauth.client("offline-client", "secret1"); + AccessTokenResponse onlineTokenResponse = oauth.doPasswordGrantRequest("manage-account-access", "password"); + Assertions.assertNull(onlineTokenResponse.getErrorDescription()); + String onlineRefreshToken = onlineTokenResponse.getRefreshToken(); + + // Create an offline session for the same client + oauth.scope(OAuth2Constants.OFFLINE_ACCESS); + AccessTokenResponse offlineTokenResponse = oauth.doPasswordGrantRequest("manage-account-access", "password"); + Assertions.assertNull(offlineTokenResponse.getErrorDescription()); + String offlineRefreshToken = offlineTokenResponse.getRefreshToken(); + + // Get an account token via direct grant + oauth.scope(null); + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("manage-account-access", "password").getAccessToken(); + + // skip the online login, the offline_access login and the direct access grant login + events.skip(3); + + UserResource user = AdminApiUtil.findUserByUsernameId(managedRealm.admin(), "manage-account-access"); + + // End the application sessions + try (SimpleHttpResponse response = simpleHttp + .doDelete(getAccountUrl("applications/offline-client/sessions")) + .header("Accept", "application/json") + .auth(token) + .asResponse()) { + Assertions.assertEquals(204, response.getStatus()); + } + + // A logout event is fired for both the online and the offline session + assertLogoutEventsForSessions(user, Set.of(onlineTokenResponse.getSessionState(), offlineTokenResponse.getSessionState())); + + // Neither the online nor the offline token can be refreshed afterwards + oauth.client("offline-client", "secret1"); + Assertions.assertEquals("invalid_grant", oauth.doRefreshTokenRequest(onlineRefreshToken).getError()); + Assertions.assertEquals("invalid_grant", oauth.doRefreshTokenRequest(offlineRefreshToken).getError()); + } + @Test public void listApplicationsThirdPartyWithoutConsentText() throws Exception { listApplicationsThirdParty("acr", false); @@ -1475,6 +1571,16 @@ public void listApplicationsWithRootUrl() throws Exception { assertClientRep(apps.get("root-url-client"), null, null, false, true, false, "http://localhost:8180/foo/bar", "/baz"); } + private Map getApplications(String token) throws IOException { + List applications = simpleHttp + .doGet(getAccountUrl("applications")) + .header("Accept", "application/json") + .auth(token) + .asJson(new TypeReference>() { + }); + return applications.stream().collect(Collectors.toMap(ClientRepresentation::getClientId, x -> x)); + } + private void assertClientRep(ClientRepresentation clientRep, String name, String description, boolean userConsentRequired, boolean inUse, boolean offlineAccess, String rootUrl, String baseUrl) { Assertions.assertNotNull(clientRep); Assertions.assertEquals(name, clientRep.getClientName()); From 8d5b735c17984240d5f08658f389be03ecde2146 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Wed, 2 Sep 2026 10:05:13 +0200 Subject: [PATCH 5/8] Tuning the docs and the UI message to avoid mixing different session types Signed-off-by: Alexander Schwartz --- docs/documentation/server_admin/topics/account.adoc | 2 +- .../theme/keycloak.v3/account/messages/messages_en.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/documentation/server_admin/topics/account.adoc b/docs/documentation/server_admin/topics/account.adoc index 433ebff4245..374a28d908e 100644 --- a/docs/documentation/server_admin/topics/account.adoc +++ b/docs/documentation/server_admin/topics/account.adoc @@ -136,7 +136,7 @@ You can end your active sessions with a specific application directly from the * . Click *End application session* next to the application. . Click *Confirm* in the confirmation dialog. -The sessions of the application for your account are ended, including any offline sessions, so the application can no longer use offline tokens to access {project_name} on your behalf. If the application supports it, {project_name} also notifies the application about the logout. Note that if your account still has an active session, for example because other applications are using it, the application might sign you in again automatically without asking for your credentials. To fully sign out from all applications, use the *Sign out* action on the *Device activity* page instead. +Your sessions with the application are ended, including any offline sessions, so the application can no longer access {project_name} on your behalf using previously issued tokens. If the application supports it, {project_name} also notifies the application. Because this does not sign you out from {project_name}, the application can sign you in again without asking for your credentials when you access it again. To fully sign out from all applications, use the *Sign out* action on the *Device activity* page instead. Ending an application session does not revoke the access you granted to the application, so it can obtain new sessions the next time you use it. To revoke the granted access, use the *Remove access* action for the application. diff --git a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties index b996b5ae75e..ef6135d6832 100644 --- a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties +++ b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/messages/messages_en.properties @@ -58,7 +58,7 @@ removeConsentError=Could not remove consent due to\: {{error}} endApplicationSession=End application session endApplicationSessionSuccess=Ended the application session for {{name}} endApplicationSessionError=Could not end the application session due to\: {{error}} -endApplicationSessionMessage=This ends your active sessions with {{name}}, including offline sessions. If your account session is still active, the application might sign you in again automatically without asking for credentials. +endApplicationSessionMessage=This ends your sessions with {{name}}, including any offline sessions. Because your browser is still signed in, the application can sign you in again without asking for your credentials when you access it again. signOutAllDevicesWarning=This action will sign out all the devices that have signed in to your account, including the current device you are using. unShareSuccess=Resource successfully un-shared. signingIn=Signing in From 4bfcde6160caed5ec0e7a6e017d02f891346cce9 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Wed, 2 Sep 2026 16:47:42 +0200 Subject: [PATCH 6/8] Copilot review Signed-off-by: Alexander Schwartz --- .../server_admin/topics/account.adoc | 2 +- js/apps/account-ui/src/api/methods.ts | 31 +++++++++++++------ .../resources/account/AccountRestService.java | 3 +- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/docs/documentation/server_admin/topics/account.adoc b/docs/documentation/server_admin/topics/account.adoc index 374a28d908e..754a6af4bc7 100644 --- a/docs/documentation/server_admin/topics/account.adoc +++ b/docs/documentation/server_admin/topics/account.adoc @@ -136,7 +136,7 @@ You can end your active sessions with a specific application directly from the * . Click *End application session* next to the application. . Click *Confirm* in the confirmation dialog. -Your sessions with the application are ended, including any offline sessions, so the application can no longer access {project_name} on your behalf using previously issued tokens. If the application supports it, {project_name} also notifies the application. Because this does not sign you out from {project_name}, the application can sign you in again without asking for your credentials when you access it again. To fully sign out from all applications, use the *Sign out* action on the *Device activity* page instead. +Your sessions with the application are ended, including any offline sessions. If the application supports it, {project_name} also notifies the application. Because this does not sign you out from {project_name}, the application can sign you in again without asking for your credentials when you access it again. To fully sign out from all applications, use the *Sign out* action on the *Device activity* page instead. Ending an application session does not revoke the access you granted to the application, so it can obtain new sessions the next time you use it. To revoke the granted access, use the *Remove access* action for the application. diff --git a/js/apps/account-ui/src/api/methods.ts b/js/apps/account-ui/src/api/methods.ts index 08c5856e499..2f868b698a6 100644 --- a/js/apps/account-ui/src/api/methods.ts +++ b/js/apps/account-ui/src/api/methods.ts @@ -91,31 +91,42 @@ export async function deleteConsent( context: KeycloakContext, id: string, ) { - return request(`/applications/${encodeURIComponent(id)}/consent`, context, { - method: "DELETE", - }); + const response = await request( + `/applications/${encodeURIComponent(id)}/consent`, + context, + { method: "DELETE" }, + ); + if (!response.ok) { + throw await parseResponse(response); + } } export async function deleteSession( context: KeycloakContext, id?: string, ) { - return request(`/sessions${id ? `/${id}` : ""}`, context, { - method: "DELETE", - }); + const response = await request( + `/sessions${id ? `/${id}` : ""}`, + context, + { method: "DELETE" }, + ); + if (!response.ok) { + throw await parseResponse(response); + } } export async function deleteApplicationSessions( context: KeycloakContext, clientId: string, ) { - return request( + const response = await request( `/applications/${encodeURIComponent(clientId)}/sessions`, context, - { - method: "DELETE", - }, + { method: "DELETE" }, ); + if (!response.ok) { + throw await parseResponse(response); + } } export async function getCredentials({ signal, context }: CallOptions) { diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java index 8df47b5a3e8..5967fe45109 100755 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java @@ -412,7 +412,8 @@ public Response revokeApplicationSessions(final @PathParam("clientId") String cl ClientModel client = realm.getClientByClientId(clientId); if (client == null) { String msg = String.format("No client with clientId: %s found.", clientId); - event.error(msg); + event.detail(Details.REASON, msg); + event.error(Errors.CLIENT_NOT_FOUND); throw ErrorResponse.error(msg, Response.Status.NOT_FOUND); } From c56f6485672f9481b9ad1448fc79cd775408c850 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Wed, 2 Sep 2026 16:51:46 +0200 Subject: [PATCH 7/8] Prevent enumeration of client IDs from the account console Signed-off-by: Alexander Schwartz --- .../services/resources/account/AccountRestService.java | 3 ++- .../org/keycloak/tests/account/AccountRestServiceTest.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java index 5967fe45109..4e0f1bab4d2 100755 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountRestService.java @@ -411,10 +411,11 @@ public Response revokeApplicationSessions(final @PathParam("clientId") String cl event.event(EventType.LOGOUT); ClientModel client = realm.getClientByClientId(clientId); if (client == null) { + // Return 204 instead of 404 to prevent client enumeration via this endpoint. String msg = String.format("No client with clientId: %s found.", clientId); event.detail(Details.REASON, msg); event.error(Errors.CLIENT_NOT_FOUND); - throw ErrorResponse.error(msg, Response.Status.NOT_FOUND); + return Response.noContent().build(); } Stream.concat(session.sessions().getUserSessionsStream(realm, user), session.sessions().getOfflineUserSessionsStream(realm, user)) diff --git a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java index 5bce2369123..d867a77d3a2 100644 --- a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java @@ -1347,12 +1347,13 @@ public void revokeApplicationSessions() throws Exception { public void revokeApplicationSessionsForNotExistingClient() throws IOException { managedRealm.cleanup().add(RealmResource::logoutAll); String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("manage-account-access", "password").getAccessToken(); + // Returns 204 instead of 404 to prevent client enumeration via this endpoint. try (SimpleHttpResponse response = simpleHttp .doDelete(getAccountUrl("applications/not-existing/sessions")) .header("Accept", "application/json") .auth(token) .asResponse()) { - Assertions.assertEquals(404, response.getStatus()); + Assertions.assertEquals(204, response.getStatus()); } } From 975cf930b4291d703349647affe95378e6855988 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Wed, 2 Sep 2026 16:51:46 +0200 Subject: [PATCH 8/8] Copilot Signed-off-by: Alexander Schwartz --- js/apps/account-ui/src/api/methods.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/js/apps/account-ui/src/api/methods.ts b/js/apps/account-ui/src/api/methods.ts index 2f868b698a6..1832fac5e86 100644 --- a/js/apps/account-ui/src/api/methods.ts +++ b/js/apps/account-ui/src/api/methods.ts @@ -99,20 +99,20 @@ export async function deleteConsent( if (!response.ok) { throw await parseResponse(response); } + return response; } export async function deleteSession( context: KeycloakContext, id?: string, ) { - const response = await request( - `/sessions${id ? `/${id}` : ""}`, - context, - { method: "DELETE" }, - ); + const response = await request(`/sessions${id ? `/${id}` : ""}`, context, { + method: "DELETE", + }); if (!response.ok) { throw await parseResponse(response); } + return response; } export async function deleteApplicationSessions( @@ -127,6 +127,7 @@ export async function deleteApplicationSessions( if (!response.ok) { throw await parseResponse(response); } + return response; } export async function getCredentials({ signal, context }: CallOptions) {