Skip to main content

Embedded Login for Web Apps

Phase Two's web SDK signs users in to Keycloak from a single-page app with the app's own screens: no redirect to Keycloak's login page and no iframe. It speaks the same challenge protocol as the iOS, Android, React Native and Flutter SDKs, so the login flow you build in the admin console, with its passwords, passkeys, one-time codes, push approvals, required actions and step-up, runs unchanged in the browser. There are four packages on npm:

  • @p2-inc/keycloak-web: the framework-free core: the login flow, tokens and DPoP, passkeys, the popup fallback, step-up for fetch, the account and organization clients, and LoginController, a UI-agnostic state machine for any framework.
  • @p2-inc/keycloak-web-react: hooks and unstyled React components: <SignIn>, <SignUp>, <StepUp>, <RequiredAction>, <StepUpBoundary> and the account widgets.
  • @p2-inc/keycloak-elements: web components with a styled default (<kc-sign-in>, <kc-profile>, <kc-credentials> and more), for any framework or none, also as a script-tag bundle.
  • @p2-inc/keycloak-web-vue: reactive auth state for Vue 3 (a createKeycloak plugin and a useKeycloak() composable). It has no UI of its own; pair it with the web components.

For apps built on shadcn/ui, a registry installs styled copies of the React components into your code.

The packages are licensed under Apache 2.0 and share one version line with the server extensions and the native SDKs; the web packages are on npm from 0.5.0. They are below 1.0, so their API may change between releases. Your Keycloak needs the native authentication extensions; see Server setup.

First-party apps only

Embedded login is for apps you publish yourself. For third-party apps, redirecting to Keycloak's login page remains the right choice, because only Keycloak's own page shows the user which site they are typing their password into. See Which should I choose?

Requirements​

  • Keycloak 26.4 or later with the native authentication extensions 0.5.0 or later. From 0.5.0 the challenge endpoint answers CORS requests from the client's Web Origins.
  • A browser with WebCrypto, IndexedDB and fetch (every current browser), on https or localhost.
  • React 18.2 or later for the React package, or Vue 3 for the Vue package.

Configure the client​

Create a public OpenID Connect client for the app, as for a native app (see Server setup), with these settings for the browser:

SettingValue
Client authenticationOff (public client)
Standard flowOn
PKCE method (Advanced tab)S256
Attribute native-auth.enabledtrue
Web originsYour app's origin, for example https://app.example.com, or + for the origins of the redirect URIs
Valid redirect URIsAn exact callback on your origin, for example https://app.example.com/callback.html
Attribute native-auth.web-fallback-redirect-uriThe same callback, used by the popup fallback

The browser only lets the app read Keycloak's responses when the app's origin is one of the client's Web Origins, so that setting is required, not optional. Set the attributes with the Admin REST API, kcadm.sh or a realm import:

{
"clientId": "my-web-app",
"publicClient": true,
"standardFlowEnabled": true,
"webOrigins": ["https://app.example.com"],
"redirectUris": ["https://app.example.com/callback.html"],
"attributes": {
"pkce.code.challenge.method": "S256",
"native-auth.enabled": "true",
"native-auth.web-fallback-redirect-uri": "https://app.example.com/callback.html"
}
}

To run a web-specific flow, set native-auth.flow-alias on the client.

Passkeys. Add your app's origin, for example https://app.example.com, to Authentication > Policies > Webauthn Passwordless Policy > Extra Origins, and make the policy's Relying Party ID a parent domain of both the app and Keycloak, for example example.com for app.example.com and auth.example.com. On Phase Two hosted Keycloak, that means serving Keycloak from a custom domain on your own domain.

Add your Keycloak origin to the page's Content Security Policy connect-src.

Install​

# React
npm install @p2-inc/keycloak-web @p2-inc/keycloak-web-react

# Web components, for any framework or none
npm install @p2-inc/keycloak-web @p2-inc/keycloak-elements

# Vue: reactive auth state, with the web components for the screens
npm install @p2-inc/keycloak-web @p2-inc/keycloak-web-vue @p2-inc/keycloak-elements

Pin exact versions: before 1.0, any release may change the API.

Quick start with React​

Create one instance per issuer and client, and keep it for the life of the page. The issuer is your realm's URL, including /realms/{realm}:

import { KeycloakWeb } from "@p2-inc/keycloak-web";
import {
KeycloakProvider,
SignIn,
StepUpBoundary,
useKeycloak,
} from "@p2-inc/keycloak-web-react";

const kc = KeycloakWeb.configure({
issuer: "https://auth.example.com/realms/{realm}",
clientId: "my-web-app",
});

function App() {
const { isAuthenticated, restoring, user, signOut } = useKeycloak();
if (restoring) return null;
if (!isAuthenticated) return <SignIn onResult={(result) => console.log(result.kind)} />;
return <button onClick={signOut}>Sign out {String(user?.name)}</button>;
}

export default function Root() {
return (
<KeycloakProvider kc={kc}>
<StepUpBoundary>
<App />
</StepUpBoundary>
</KeycloakProvider>
);
}

KeycloakProvider restores a stored session on mount, so a reload keeps the user signed in, and finishes a full-page fallback that returned to the app. <SignIn> renders the flow Keycloak sends, one challenge at a time, with "Try another way" for the alternatives. When the realm allows registration and password reset and has the native registration flows, it also offers "Create an account" and "Forgot password?"; <SignUp> and <ResetPassword> are the same screens on their own.

Style and replace screens​

The React components ship without CSS. Every element carries a data-kc-part attribute (root, title, form, field, label, input, error, submit and more) and forms carry data-kc-challenge="<type>", so you style them from your own stylesheet. To replace the screen of one challenge type and keep the rest, pass components:

import type { ChallengeProps } from "@p2-inc/keycloak-web-react";

function MyPassword({ challenge, submit, isSubmitting }: ChallengeProps<"password">) {
// Render your own form, then answer with submit({ kind: "password", password }).
}

<SignIn components={{ password: MyPassword }} />;

To take over the whole layout, use render, or drive the flow yourself with useLogin(). Strings are English by default; pass strings to KeycloakProvider or a component to replace some or all of them.

shadcn/ui​

For apps on shadcn/ui, the registry copies styled versions of the React components into your app, where you own and edit them. The flow logic stays in the package, so Keycloak can still change the login flow without a release of your app:

npx shadcn@latest add https://raw.githubusercontent.com/p2-inc/native-apps/main/web/registry/public/r/keycloak-sign-in.json
npx shadcn@latest add https://raw.githubusercontent.com/p2-inc/native-apps/main/web/registry/public/r/keycloak-account.json

@/components/keycloak-sign-in then has SignIn, SignUp, ResetPassword, StepUp, RequiredAction and StepUpDialog as shadcn cards and dialogs, and @/components/keycloak-account has Profile, Credentials, Sessions and OrganizationSwitcher. They take the same props as the package's components. To pin a release, replace main in the URL with its tag, for example 0.5.0. The items work with shadcn/ui on Base UI (the default) and on Radix; on the React Aria base, use the unstyled components of @p2-inc/keycloak-web-react instead.

Web components​

@p2-inc/keycloak-elements puts the same screens in any page, with any framework or none, and with a styled default. One configure() call connects every element on the page, restores the stored session, adds the default theme and a step-up dialog, and returns the KeycloakWeb instance:

<kc-signed-out>
<kc-sign-in heading="Sign in to Example"></kc-sign-in>
</kc-signed-out>
<kc-signed-in>
<kc-profile></kc-profile>
<kc-credentials></kc-credentials>
<kc-sessions></kc-sessions>
</kc-signed-in>

<script type="module">
import { configure } from "@p2-inc/keycloak-elements";

const kc = configure({
issuer: "https://auth.example.com/realms/{realm}",
clientId: "my-web-app",
});
document
.querySelector("kc-sign-in")
.addEventListener("kc-result", (event) => console.log(event.detail.kind));
</script>

Without a build step, load the script-tag bundle (the elements, the SDK and Lit in one file) and use the global KeycloakElements:

<script src="https://cdn.jsdelivr.net/npm/@p2-inc/keycloak-elements@0.5.0/dist/keycloak-elements.iife.js"></script>
<script>
KeycloakElements.configure({
issuer: "https://auth.example.com/realms/{realm}",
clientId: "my-web-app",
});
</script>

<kc-signed-in> and <kc-signed-out> show their children by sign-in state, and both stay hidden while the session is restored, so a signed-in user doesn't see the sign-in form flash. The other elements are <kc-sign-up>, <kc-reset-password>, <kc-step-up>, <kc-required-action> and <kc-organization-switcher>. Results arrive as DOM events: kc-result from the login elements, kc-saved from <kc-profile>, kc-changed from <kc-credentials> and <kc-sessions>, and kc-switched from <kc-organization-switcher>.

The elements render in the light DOM, not in a shadow root, so password managers, autofill, passkey autofill and <label for> work as in any form, and your page's CSS reaches every part. The default theme sits in its own cascade layer with zero-specificity selectors, so any rule of the page wins. Change it through custom properties:

kc-sign-in,
kc-profile {
--kc-color-accent: #0f766e;
--kc-radius: 4px;
--kc-font: "Inter", sans-serif;
}

Every element also takes theme="light|dark" (by default it follows the system) and unstyled. For a strict style-src policy, turn off the injected styles and link @p2-inc/keycloak-elements/theme.css instead.

Vue, Angular and Svelte​

In any framework other than React, use the web components for the screens and keep the auth state in the framework's own reactivity. For Vue 3, @p2-inc/keycloak-web-vue provides that state:

// main.ts
import { createApp } from "vue";
import { configure } from "@p2-inc/keycloak-elements";
import { createKeycloak } from "@p2-inc/keycloak-web-vue";
import App from "./App.vue";

// configure() creates the instance, connects the elements and restores the session.
const kc = configure({
issuer: "https://auth.example.com/realms/{realm}",
clientId: "my-web-app",
});

createApp(App).use(createKeycloak(kc, { restore: false })).mount("#app");
<script setup lang="ts">
import { useKeycloak } from "@p2-inc/keycloak-web-vue";

const { isAuthenticated, user, signOut } = useKeycloak();
</script>

<template>
<p v-if="isAuthenticated">
Signed in as {{ user?.preferred_username }}
<button @click="signOut()">Sign out</button>
</p>
<kc-sign-in v-else heading="Sign in to Example" />
</template>

Tell Vue's template compiler that kc-* tags are custom elements, with compilerOptions.isCustomElement = (tag) => tag.startsWith("kc-") in @vitejs/plugin-vue. Because configure() already restores the session, the plugin skips its own restore (restore: false); listen for the kc-restored event on document if you need to know when restoring has finished.

Angular needs CUSTOM_ELEMENTS_SCHEMA in the components that use the elements, and Svelte needs no configuration. In every framework, bind objects such as parameters as properties and listen to the DOM events. The Vue, Angular and Svelte guide on GitHub has a complete example for each, including Nuxt, SvelteKit and Angular with server-side rendering.

The SDK keeps the session in the browser, so in a server-rendered app (Next.js, Nuxt, SvelteKit, Angular SSR, Remix) render the sign-in and account screens on the client, and call APIs from the browser.

Both are optional server modules (see Server setup).

Organization selection. With Phase Two's organizations extension and native-select-org in the flow, the user can choose the organization to sign in to. Pass parameters={{ prompt: "select_account" }} to <SignIn>, and a user with several organizations picks one; pass parameters={{ accountHint: organizationId }} to sign in to a known organization without asking. The picker is the organization_select challenge, replaceable through components like any other screen. After sign-in, the organization switcher changes the active organization.

Magic link. With Phase Two's magic link extension and native-magic-link in the flow, <SignIn> offers "Email me a sign-in link" next to the password. After the user sends it, the screen waits and signs the user in as soon as they open the link, in any browser, on this device or another. Without the components, answer the magic_link challenge with { kind: "magicLinkSend" } and { kind: "magicLinkPoll" }; LoginController polls for you.

Account widgets​

Drop-in screens for the signed-in user, on Keycloak's account API. Each renders nothing while nobody is signed in:

import {
Credentials,
OrganizationSwitcher,
Profile,
Sessions,
} from "@p2-inc/keycloak-web-react";

<OrganizationSwitcher />
<Profile />
<Credentials />
<Sessions />
  • <Profile> shows and saves the realm's user profile, with its labels, required and read-only attributes and validation.
  • <Credentials> lists how the user signs in (password, authenticator apps, passkeys, recovery codes, and the PIN and push approval of Phase Two's extensions), with add, change, rename and remove. Removing a credential asks the user to confirm it's them first when they signed in more than five minutes ago.
  • <Sessions> lists where the user is signed in, with sign-out per session and "Sign out everywhere else".
  • <OrganizationSwitcher> lists the user's organizations and switches the active one, refreshing the tokens so the active_organization claim follows. It renders nothing without the organizations extension.

The web components are <kc-profile>, <kc-credentials>, <kc-sessions> and <kc-organization-switcher>. Without the components, use kc.account() and kc.organizations().

The access token needs the account audience, which Keycloak adds when the user has the account client's manage-account role (part of the realm's default roles) and the client has the roles scope (a default scope).

Step-up and calling your API​

kc.fetch(url, init) calls your API with the user's token: Authorization: DPoP … with a proof when the token is DPoP-bound. When the API answers with an RFC 9470 step-up challenge (WWW-Authenticate: Bearer error="insufficient_user_authentication", acr_values="2"), <StepUpBoundary> (or StepUpDialog from the registry, or the elements' built-in dialog) asks for the stronger factor and retries the request once it succeeds.

const response = await kc.fetch("https://api.example.com/transfers", { method: "POST", body });

To ask for a step-up yourself, <StepUp acrValues="2" /> asks only for what the requested level still needs, and <StepUp maxAge={0} /> asks for every factor again ("Confirm it's you"). <RequiredAction alias="UPDATE_PASSWORD" /> runs a required action for the signed-in user, such as a "Change password" button, and reports whether it succeeded, was cancelled or failed.

Passkeys​

A passkey challenge shows "Continue with a passkey". When the flow offers a discoverable passkey next to the username, the username field also lists passkeys in the browser's autofill. To add a passkey after sign-in, from a settings screen:

await kc.registerNewPasskey("My laptop");

If the user signed in too long ago, Keycloak refuses until they step up; run <StepUp maxAge={0} /> and try again.

The browser fallback​

Steps without a native variant, such as a required action without a native screen or an identity provider login, hand the login to Keycloak's own pages. <SignIn> then offers to open a window: Keycloak's page opens in a popup, and when it reaches your callback the popup closes and the app is signed in. If the browser blocks the popup, the SDK falls back to a full-page redirect and finishes the login when the app loads again.

Serve the callback page at the URI in native-auth.web-fallback-redirect-uri:

<!-- callback.html -->
<script type="module">
import { completeWebFallbackPopup } from "@p2-inc/keycloak-web";
// In a popup, this hands the result to the app and closes the window.
// After a full-page redirect, return to the app, which finishes the login.
if (!completeWebFallbackPopup()) location.replace("/" + location.search + location.hash);
</script>

An embedded sign-in sets no Keycloak cookie in the browser, so Keycloak's page in the popup asks the user to sign in there too. With the SSO cookie session on, it goes straight to the step instead.

Available from 0.6.0

The SSO cookie session needs the native authentication extensions and the web packages at 0.6.0 or later.

By default an embedded sign-in signs in only your app: Keycloak's own pages, such as your other apps on the realm, the account console and the browser fallback, don't know the user. The SSO cookie session signs the browser in to Keycloak too, for the same user session as your app, so those pages know the user without asking again.

For the best experience, put Keycloak on a custom domain that matches your app's domain, for example auth.example.com for an app on app.example.com. The SDK then signs the browser in to Keycloak in the background right after the embedded sign-in, with no redirect and no popup. On Phase Two hosted Keycloak, serve Keycloak from a custom domain on your own domain; passkeys want the same setup.

Set it up​

On the client, set the attribute native-auth.web-sso-cookie to true. The client also needs native-auth.web-fallback-redirect-uri set to an exact callback on your app's origin, listed among its Valid redirect URIs (see Configure the client). Its origin is the only one Keycloak accepts SSO cookie requests from.

"attributes": {
"pkce.code.challenge.method": "S256",
"native-auth.enabled": "true",
"native-auth.web-fallback-redirect-uri": "https://app.example.com/callback.html",
"native-auth.web-sso-cookie": "true"
}

In the SDK, set ssoCookie: "fetch" and, optionally, onSsoCookie to learn the outcome:

const kc = KeycloakWeb.configure({
issuer: "https://auth.example.com/realms/{realm}",
clientId: "my-web-app",
ssoCookie: "fetch",
onSsoCookie: (result) => {
// { status: "set" }, or { status: "refused", reason: "cross_site_blocked" | <error code> }
},
});

After each sign-in, sign-up or password reset, once onResult has run, the SDK exchanges a one-time code with Keycloak in a background fetch, checks that the browser kept Keycloak's cookie, and reports the outcome to onSsoCookie: set, or refused with a reason such as cross_site_blocked, unauthorized_client (the client setting is off) or network_error. The page doesn't move. kc.setSsoCookie() does the same on demand and resolves with the same result. A refusal never affects your app's own session.

Keep DPoP on, which is the default. Keycloak issues the one-time code only to a DPoP-bound session, so a copied session value alone can't sign a browser in. If your app turns DPoP off, the client must also set native-auth.web-sso-cookie-allow-without-dpop to true; otherwise the SDK reports refused with invalid_dpop_proof.

Without a matching custom domain​

Keycloak's cookies live on Keycloak's host, and whether the browser keeps a cookie from a background request depends on the site: the scheme plus the registrable domain. Subdomains and ports don't count, so auth.example.com and app.example.com are the same site even though they are different hosts.

KeycloakYour appSame site?ssoCookie: "fetch"
auth.example.com (custom domain)app.example.comYesset in every browser
auth.example.comexample.comYesset in every browser
A provider's domain, for example acme.keycloak-host.exampleapp.example.comNoDepends on the browser's third-party cookie rules

On another site, the browser treats Keycloak's cookie as a third-party cookie: Safari blocks it, Chrome keeps it while third-party cookies are allowed, and Firefox may keep it only in a partition for your app's site, where Keycloak's own pages don't see it. When the browser didn't keep it, the SDK reports refused with cross_site_blocked and never navigates on its own.

Until Keycloak is on a matching custom domain, set the cookie in a top-level navigation, which every browser treats as first-party:

  • Popup. Call kc.setSsoCookie({ mode: "popup" }) from a click, for example on an "Account settings" button that then opens the account console. A small popup sets the cookie and closes; the page stays. ssoCookie: "popup" also tries this right after a quick sign-in, while the click still counts.
  • Redirect. With ssoCookie: "redirect", the page goes through Keycloak and back to your callback page after each sign-in, and the SDK restores the session and the URL the user was on. The app reloads once per sign-in, and it needs the default IndexedDB storage.
const result = await kc.setSsoCookie();
if (result.status === "refused" && result.reason === "cross_site_blocked") {
// Offer a button whose click handler calls kc.setSsoCookie({ mode: "popup" })
}

Sign-out​

With ssoCookie set to any mode, kc.signOut() ends the whole Keycloak session, including every app that joined it through the browser, like keycloak-js logout(). Signing out in another app or the account console ends your app's session at its next refresh.

Tokens, DPoP and sign-out​

WhatWhere
Access token, ID tokenMemory
Refresh tokenIndexedDB, bound by DPoP to the key below
DPoP private keyIndexedDB, as a non-extractable WebCrypto key: the page can use it but can't read or copy it
  • DPoP. The SDK binds the refresh token and the access token to its key, so a refresh token copied off the page is useless without it. Tokens are bound once Keycloak's DPoP feature is on; your APIs must then accept Authorization: DPoP and check the proof (see Server setup).
  • Sessions. An embedded sign-in creates a Keycloak user session on the server, and the stored refresh token keeps the user signed in across reloads until the realm's SSO idle or maximum lifetime ends that session. Refreshes are serialized across tabs, and every tab of the origin follows sign-in, refresh and sign-out. Configure storage: "memory" to keep nothing across reloads.
  • Sign-out. kc.signOut() revokes the refresh token, which ends the Keycloak session, and forgets the key. With the SSO cookie session on, it ends the whole Keycloak session.
  • Browser single sign-on. By default the embedded sign-in sets no Keycloak cookie, so other apps and Keycloak's own pages don't see the session. Turn on the SSO cookie session to share it.

Full guide​

The web integration guide on GitHub covers every component, element and option, the theme's custom properties, driving the flow without React, and running the demo app against a local Keycloak. The registry's README covers the shadcn/ui items, and the Vue, Angular and Svelte guide the other frameworks.