8000 Enable DPoP for Admin and Account Consoles by edewit · Pull Request #54676 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,17 @@ When upgrading, existing `aes-generated` key providers without an explicit `secr
This ensures the Admin Console displays the actual key size and saving a provider without changes preserves its key and key ID.
Providers with an explicitly configured size are preserved.

=== Admin and Account Consoles use DPoP-bound tokens when advertised
// https://github.com/keycloak/keycloak/issues/42813
// https://github.com/keycloak/keycloak/issues/42814

The Admin Console and Account Console now initialize `keycloak-js` with DPoP in `auto` mode and send authenticated API requests through `keycloak.fetch`.
When the server advertises DPoP support, console access tokens are DPoP-bound and must be presented with a DPoP proof.
Plain `Authorization: Bearer` requests that reuse the console token without a proof are rejected.

If you maintain console extensions or custom themes that call `fetch` with `keycloak.token` directly, switch those calls to `keycloak.fetch` (or an equivalent that attaches a DPoP proof) so they keep working when DPoP is active.
When the server does not advertise DPoP, the consoles continue to use Bearer tokens as before.

=== SAML assertions with a OneTimeUse condition are no longer replayable
// https://github.com/keycloak/keycloak/issues/46325

Expand Down
2 changes: 1 addition & 1 deletion js/apps/account-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@patternfly/react-table": "^6.7.0",
"i18next": "^25.7.3",
"i18next-fetch-backend": "^7.0.0",
"keycloak-js": "^26.2.2",
"keycloak-js": "^26.2.5",
"lodash-es": "^4.18.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand Down
14 changes: 11 additions & 3 deletions js/apps/account-ui/src/api/request.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
createKeycloakFetch,
KeycloakContext,
type BaseEnvironment,
} from "@keycloak/keycloak-ui-shared";
Expand All @@ -17,6 +18,7 @@ export type RequestOptions = {

async function _request(
url: URL,
keycloak: Keycloak,
{ signal, getAccessToken, method, searchParams, body }: RequestOptions = {},
): Promise<Response> {
if (searchParams) {
Expand All @@ -25,13 +27,19 @@ async function _request(
);
}

return fetch(url, {
// Refresh first, then read keycloak.token at the last moment so a concurrent
// refresh cannot make keycloak.fetch skip the Bearer→DPoP upgrade.
await getAccessToken?.();

// Route through createKeycloakFetch so Request normalization and a single
// 401 retry cover keycloak-js proof/Authorization races.
return createKeycloakFetch(keycloak)(url, {
signal,
method,
body: body ? JSON.stringify(body) : undefined,
headers: {
[CONTENT_TYPE_HEADER]: CONTENT_TYPE_JSON,
authorization: `Bearer ${await getAccessToken?.()}`,
authorization: `Bearer ${keycloak.token}`,
},
});
}
Expand All @@ -45,7 +53,7 @@ export async function request(
if (typeof fullUrl === "undefined") {
fullUrl = url(environment, path);
}
return _request(fullUrl, {
return _request(fullUrl, keycloak, {
...opts,
getAccessToken: token(keycloak),
});
Expand Down
2 changes: 1 addition & 1 deletion js/apps/admin-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@
"i18next": "^25.7.3",
"i18next-fetch-backend": "^7.0.0",
"jszip": "^3.10.1",
"keycloak-js": "^26.2.2",
"keycloak-js": "^26.2.5",
"lodash-es": "^4.18.1",
"p-debounce": "^5.1.0",
"react": "^18.3.1",
Expand Down
17 changes: 13 additions & 4 deletions js/apps/admin-ui/src/admin-client.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import KeycloakAdminClient from "@keycloak/keycloak-admin-client";
import KeycloakAdminClient, {
type DpopAwareFetch,
} from "@keycloak/keycloak-admin-client";
import {
createKeycloakFetch,
createNamedContext,
KeycloakSpinner,
useEnvironment,
Expand All @@ -9,9 +12,12 @@ import type Keycloak from "keycloak-js";
import { PropsWithChildren, useEffect, useState } from "react";
import type { Environment } from "./environment-types";

/** Admin Console client always constructed with a DPoP-aware fetch. */
export type AdminClient = KeycloakAdminClient<DpopAwareFetch>;

export type AdminClientProps = {
keycloak: Keycloak;
adminClient: KeycloakAdminClient;
adminClient: AdminClient;
};

export const AdminClientContext = createNamedContext<
Expand All @@ -24,9 +30,12 @@ export async function initAdminClient(
keycloak: Keycloak,
environment: Environment,
) {
const adminClient = new KeycloakAdminClient();
const adminClient = new KeycloakAdminClient({
fetch: createKeycloakFetch(keycloak),
});
Comment thread
edewit marked this conversation as resolved.
Resolved

adminClient.setConfig({ realmName: environment.realm });

adminClient.baseUrl = environment.adminBaseUrl;
adminClient.registerTokenProvider({
async getAccessToken() {
Expand All @@ -45,7 +54,7 @@ export async function initAdminClient(

export const AdminClientProvider = ({ children }: PropsWithChildren) => {
const { keycloak, environment } = useEnvironment<Environment>();
const [adminClient, setAdminClient] = useState<KeycloakAdminClient>();
const [adminClient, setAdminClient] = useState<AdminClient>();

useEffect(() => {
const init = async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchWithError } from "@keycloak/keycloak-admin-client";
import { fetchWithError } from "../utils/fetchWithError";
import {
KeycloakDataTable,
ListEmptyState,
Expand Down Expand Up @@ -70,7 +70,7 @@

useEffect(() => {
refreshRealm();
}, []);

Check warning on line 73 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

React Hook useEffect has a missing dependency: 'refreshRealm'. Either include it or remove the dependency array
const [key, setKey] = useState(0);
const refresh = () => setKey(key + 1);
const { addAlert, addError } = useAlerts();
Expand All @@ -88,6 +88,7 @@
method: "GET",
headers: getAuthorizationHeaders(await adminClient.getAccessToken()),
},
adminClient.getFetch(),
);
const flows = await flowsRequest.json();

Expand All @@ -102,11 +103,11 @@
};

const useTab = (tab: AuthenticationTab) =>
useRoutableTab(toAuthentication({ realm: realmName, tab }));

Check warning on line 106 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

Hooks must be called at the top level in the body of a function component or custom hook, and may not be called within function expressions. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)

const flowsTab = useTab("flows");

Check warning on line 108 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks
const requiredActionsTab = useTab("required-actions");

Check warning on line 109 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks
const policiesTab = useTab("policies");

Check warning on line 110 in js/apps/admin-ui/src/authentication/AuthenticationSection.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks

const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: "deleteConfirmFlow",
Expand Down
3 changes: 2 additions & 1 deletion js/apps/admin-ui/src/authentication/RequiredActions.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchWithError } from "@keycloak/keycloak-admin-client";
import { fetchWithError } from "../utils/fetchWithError";
import type RequiredActionProviderRepresentation from "@keycloak/keycloak-admin-client/lib/defs/requiredActionProviderRepresentation";
import type RequiredActionProviderSimpleRepresentation from "@keycloak/keycloak-admin-client/lib/defs/requiredActionProviderSimpleRepresentation";
import { useAlerts, useFetch } from "@keycloak/keycloak-ui-shared";
Expand Down Expand Up @@ -49,6 +49,7 @@ export const RequiredActions = () => {
method: "GET",
headers: getAuthorizationHeaders(await adminClient.getAccessToken()),
},
adminClient.getFetch(),
);

return (await requiredActionsRequest.json()) as DataType[];
Expand Down
3 changes: 2 additions & 1 deletion js/apps/admin-ui/src/clients/import/ImportForm.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchWithError } from "@keycloak/keycloak-admin-client";
import { fetchWithError } from "../../utils/fetchWithError";
import type ClientRepresentation from "@keycloak/keycloak-admin-client/lib/defs/clientRepresentation";
import {
ActionGroup,
Expand Down Expand Up @@ -70,6 +70,7 @@ export default function ImportForm() {
body: contents,
headers: getAuthorizationHeaders(await adminClient.getAccessToken()),
},
adminClient.getFetch(),
);

if (!response.ok) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchWithError } from "@keycloak/keycloak-admin-client";
import { fetchWithError } from "../../utils/fetchWithError";
import { HelpItem, useFetch, useHelp } from "@keycloak/keycloak-ui-shared";
import {
Form,
Expand Down Expand Up @@ -73,6 +73,7 @@ export const DownloadDialog = ({
await adminClient.getAccessToken(),
),
},
adminClient.getFetch(),
);

return response.arrayBuffer();
Expand Down
9 changes: 5 additions & 4 deletions js/apps/admin-ui/src/components/role-mapping/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { Clients } from "@keycloak/keycloak-admin-client/lib/resources/clie
import type { Groups } from "@keycloak/keycloak-admin-client/lib/resources/groups";
import type { Roles } from "@keycloak/keycloak-admin-client/lib/resources/roles";
import type { Users } from "@keycloak/keycloak-admin-client/lib/resources/users";
import type { AdminClient } from "../../admin-client";
import {
deleteRoleMappings,
getAllEffectiveRoles,
Expand Down Expand Up @@ -97,7 +98,7 @@ const mapping: ResourceMapping = {
};

export const deleteMapping = (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
type: ResourcesKey,
id: string,
rows: Row[],
Expand All @@ -112,7 +113,7 @@ export const deleteMapping = (
};

export const getMapping = async (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
type: ResourcesKey,
id: string,
groupsResource?: any,
Expand All @@ -134,7 +135,7 @@ export const getMapping = async (
};

export const getEffectiveRoles = async (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
type: ResourcesKey,
id: string,
): Promise<Row[]> => {
Expand All @@ -151,7 +152,7 @@ export const getEffectiveRoles = async (
};

export const getAvailableRoles = async (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
type: ResourcesKey,
params: Record<string, string | number>,
groupsResource?: any,
Expand Down
18 changes: 9 additions & 9 deletions js/apps/admin-ui/src/components/role-mapping/resource.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type UserRepresentation from "@keycloak/keycloak-admin-client/lib/defs/userRepresentation";

import type { AdminClient } from "../../admin-client";
import {
fetchAdminUI,
postAdminUI,
} from "../../context/auth/admin-ui-endpoint";
import KeycloakAdminClient from "@keycloak/keycloak-admin-client";

type IDQuery = {
id: string;
Expand Down Expand Up @@ -41,7 +41,7 @@ export type EffectiveRole = {
};

const fetchEndpoint = async (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
{ id, type, first, max, search, endpoint }: Query,
): Promise<any> =>
fetchAdminUI(
Expand All @@ -55,19 +55,19 @@ const fetchEndpoint = async (
);

export const getAvailableClientRoles = (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
query: PaginatingQuery,
): Promise<ClientRole[]> =>
fetchEndpoint(adminClient, { ...query, endpoint: "available-roles" });

export const getEffectiveClientRoles = (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
query: EffectiveClientRolesQuery,
): Promise<ClientRole[]> =>
fetchEndpoint(adminClient, { ...query, endpoint: "effective-roles" });

export const getAllEffectiveRoles = (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
query: EffectiveClientRolesQuery,
): Promise<EffectiveRole[]> =>
fetchEndpoint(adminClient, { ...query, endpoint: "effective-roles-all" });
Expand All @@ -93,7 +93,7 @@ export type RoleMappingRepresentation = {
};

export const getRoleMappings = async (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
id: string,
): Promise<RoleMappingRepresentation> =>
fetchAdminUI(
Expand All @@ -109,7 +109,7 @@ export type RoleDeleteRequest = {
};

export const deleteRoleMappings = async (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
type: string,
id: string,
roles: RoleDeleteRequest[],
Expand Down Expand Up @@ -140,7 +140,7 @@ export type BruteUser = UserRepresentation & {
};

export const findUsers = (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
query: UserQuery,
): Promise<BruteUser[]> =>
fetchAdminUI(
Expand All @@ -160,7 +160,7 @@ export type UsedByReference = {
};

export const fetchUsedBy = (
adminClient: KeycloakAdminClient,
adminClient: AdminClient,
query: PaginatingQuery,
): Promise<UsedByReference[]> =>
fetchEndpoint(adminClient, {
Expand Down
18 changes: 8 additions & 10 deletions js/apps/admin-ui/src/context/auth/admin-ui-endpoint.test.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
import KeycloakAdminClient from "@keycloak/keycloak-admin-client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import KeycloakAdminClient, {
asDpopAwareFetch,
} from "@keycloak/keycloak-admin-client";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AdminClient } from "../../admin-client";
import { fetchAdminUI, postAdminUI } from "./admin-ui-endpoint";

describe("admin-ui-endpoint", () => {
let adminClient: KeycloakAdminClient;
let adminClient: AdminClient;
let fetchMock: ReturnType<typeof vi.fn>;

beforeEach(() => {
fetchMock = vi.fn().mockResolvedValue(new Response("{}"));
adminClient = new KeycloakAdminClient({
baseUrl: "http://localhost:8080",
realmName: "test",
requestOptions: { headers: { "X-Custom-Header": "custom" } },
fetch: asDpopAwareFetch(fetchMock),
});
adminClient.registerTokenProvider({
getAccessToken: () => Promise.resolve("token"),
});

fetchMock = vi.fn().mockResolvedValue(new Response("{}"));
vi.stubGlobal("fetch", fetchMock);
});

afterEach(() => {
vi.unstubAllGlobals();
});

const sentHeaders = () => new Headers(fetchMock.mock.calls[0][1].headers);
Expand Down
Loading
Loading
0