RealmDeployDocs
GuidesFramework quickstarts

Add Keycloak login to an Angular app

Add Keycloak login to an Angular 22 app with angular-oauth2-oidc, the standalone provideOAuthClient API, and the code flow with PKCE.

An Angular app signs users in with the authorization code flow and PKCE through angular-oauth2-oidc. It runs entirely in the browser and cannot keep a secret, so the client is public.

Written against angular-oauth2-oidc 22.0.2, Angular 22.3, jose 6.2 and Keycloak 26.8, checked on 25 November 2026. The library's major version follows Angular's: its README pairs Angular 22 with the 22.x releases, and 22.0.2 declares @angular/core 22 or newer as its peer. On an older Angular, install the matching major, for example angular-oauth2-oidc@21 for Angular 21.

Replace auth.example.com with your RealmDeploy hostname and acme with your realm.

Create the client in Keycloak

Open Clients, choose Create client, and use these values:

SettingValue
Client typeOpenID Connect
Client IDangular-app
Client authenticationOff
Authentication flowStandard flow. Turn Direct access grants off.
PKCE MethodS256
Root URLhttp://localhost:4200
Valid redirect URIshttp://localhost:4200/
Valid post logout redirect URIshttp://localhost:4200/
Web originshttp://localhost:4200

Choose Save. A public client has no Credentials tab and no secret.

Web origins matters here: the browser calls Keycloak's token endpoint from JavaScript, and Keycloak answers that cross-origin request only for the origins listed. The Web origins helper explains the values.

For production, add your app's real URLs next to the local ones, for example https://app.example.com/ and the origin https://app.example.com. Keycloak compares redirect URIs exactly.

Environment variables

Angular has no .env file; the CLI's convention is an environment file. Create it by hand:

src/environments/environment.ts
export const environment = {
  issuer: 'https://auth.example.com/realms/acme',
  clientId: 'angular-app',
  apiUrl: 'http://localhost:3000/api',
};

These values end up in the JavaScript bundle, so put only public values here. A public client has nothing secret to hide. For different values per build, run ng generate environments and use the file replacements it sets up.

Install

npx @angular/cli@22 new angular-app --defaults --ssr=false
cd angular-app
npm install angular-oauth2-oidc

--ssr=false keeps the app browser-only, because the code below reads window and the tokens live in the browser.

Add login

Replace the generated src/app/app.config.ts. The library's standalone API is provideOAuthClient; the app initializer loads Keycloak's discovery document and finishes a login that comes back with ?code=... before the app renders.

src/app/app.config.ts
import {
  ApplicationConfig,
  inject,
  provideAppInitializer,
  provideBrowserGlobalErrorListeners,
} from '@angular/core';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { AuthConfig, OAuthService, provideOAuthClient } from 'angular-oauth2-oidc';
import { routes } from './app.routes';
import { environment } from '../environments/environment';

const authConfig: AuthConfig = {
  issuer: environment.issuer,
  clientId: environment.clientId,
  responseType: 'code', // authorization code flow; PKCE is on by default
  redirectUri: window.location.origin + '/',
  postLogoutRedirectUri: window.location.origin + '/',
  scope: 'openid profile email',
};

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes),
    // The library's interceptor is class-based, so enable DI interceptors.
    provideHttpClient(withInterceptorsFromDi()),
    provideOAuthClient({
      resourceServer: {
        allowedUrls: [environment.apiUrl],
        sendAccessToken: true,
      },
    }),
    provideAppInitializer(async () => {
      const oauth = inject(OAuthService);
      oauth.configure(authConfig);
      // Loads the discovery document and, when the URL holds ?code=...,
      // exchanges the code for tokens.
      await oauth.loadDiscoveryDocumentAndTryLogin();
    }),
  ],
};

Then replace src/app/app.ts:

src/app/app.ts
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { OAuthService } from 'angular-oauth2-oidc';
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  template: `
    @if (loggedIn) {
      <p>Signed in as {{ username }}</p>
      <button (click)="callApi()">Call API</button>
      <button (click)="logout()">Log out</button>
    } @else {
      <button (click)="login()">Log in</button>
    }
  `,
})
export class App {
  private readonly oauth = inject(OAuthService);
  private readonly http = inject(HttpClient);

  get loggedIn() {
    return this.oauth.hasValidAccessToken();
  }

  get username() {
    return this.oauth.getIdentityClaims()?.['preferred_username'];
  }

  login() {
    this.oauth.initCodeFlow();
  }

  logout() {
    // Clears the tokens, then redirects to Keycloak's end-session
    // endpoint with id_token_hint and post_logout_redirect_uri.
    this.oauth.logOut();
  }

  callApi() {
    // The library's interceptor adds the access token for allowedUrls.
    this.http.get(`${environment.apiUrl}/me`).subscribe((data) => console.log(data));
  }
}

Run npm start, open http://localhost:4200 and sign in with a user of your realm. The generated app.html and app.css are no longer used; delete them if you like.

The library keeps the tokens in the browser's sessionStorage by default, which any script on the page can read. That is the trade-off of a pure single-page app; for apps that handle sensitive data, put a backend-for-frontend in front of it that keeps the tokens on the server and gives the browser only a session cookie, as in the Express guide.

Protect an API

With sendAccessToken: true, the library's interceptor adds Authorization: Bearer <access token> to every HttpClient request whose URL starts with one of allowedUrls, and to no other. The API must check the token's signature, issuer and audience before it trusts it.

Keycloak does not put your API in the access token's aud claim by default, so add an Audience mapper to this client:

  1. Open Clients, choose angular-app, and open its Client scopes tab.
  2. Choose angular-app-dedicated.
  3. Choose Configure a new mapper (or Add mapper → By configuration), then Audience.
  4. Enter a Name, set Included Custom Audience to orders-api, keep Add to access token on, and choose Save.

Sign in again to get a token with the new audience. On the API side, a Node.js check with jose looks like this (set OIDC_ISSUER to https://auth.example.com/realms/acme and API_AUDIENCE to orders-api):

api/verify-token.ts
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose"

const issuer = process.env.OIDC_ISSUER!
const audience = process.env.API_AUDIENCE

// The realm's public signing keys. jose caches them and fetches
// them again when a token arrives with a key ID it has not seen.
const jwks = createRemoteJWKSet(new URL(`${issuer}/protocol/openid-connect/certs`))

export async function verifyBearerToken(request: Request): Promise<JWTPayload | null> {
  // jose skips the audience check when audience is undefined, so fail loudly.
  if (!audience) throw new Error("API_AUDIENCE is not set")

  const header = request.headers.get("authorization")
  if (!header?.startsWith("Bearer ")) return null

  try {
    const { payload } = await jwtVerify(header.slice("Bearer ".length), jwks, {
      issuer,
      audience,
    })
    return payload
  } catch {
    return null
  }
}

It takes a standard Request, so it fits any runtime with the Fetch API. For an Express middleware, see Protect an API in the Express guide. Your API on another origin must also answer CORS requests from http://localhost:4200; the CORS checker shows what it sends back.

Log out

logOut() clears the stored tokens, then sends the browser to the realm's end-session endpoint (taken from the discovery document) with the ID token as id_token_hint and postLogoutRedirectUri. Keycloak ends its session without asking and sends the user back to http://localhost:4200/, which must be listed in Valid post logout redirect URIs.

logOut(true) only clears the tokens in the browser. The Keycloak session stays, and the next login goes straight through without a password.

Common errors

ErrorCauseFix
Keycloak shows Invalid parameter: redirect_urihttp://localhost:4200/ is not in Valid redirect URIs, or differs in scheme, port or trailing slash.Add it exactly. Compare both with the redirect URI matcher.
Console: invalid issuer in discovery documentissuer differs from the issuer in the discovery document, often by a trailing slash.Use https://auth.example.com/realms/acme exactly. Compare with the OIDC discovery viewer.
Browser console: the token request was blocked by CORS policyThe app's origin is not in Web origins.Add http://localhost:4200, without a path or trailing slash.
Token request fails with unauthorized_clientClient authentication is on, so Keycloak expects a secret.Turn Client authentication off for this client.
Keycloak shows Invalid redirect uri after Log outpostLogoutRedirectUri is not in Valid post logout redirect URIs.Add http://localhost:4200/.
API requests go out without a tokenThe request URL does not start with an entry in allowedUrls, or withInterceptorsFromDi() is missing.Check both in app.config.ts.
API returns 401, jose says unexpected "aud" claim valueThe access token has no orders-api audience.Add the Audience mapper above and sign in again.

Decode a token with the JWT decoder to see its iss, aud and expiry. For other OAuth error codes, see the OAuth error lookup.

FAQ

Does the token renew itself?

Not with this setup. Call this.oauth.setupAutomaticSilentRefresh() after login; in the code flow the library then uses the refresh token Keycloak issues.

Why not loadDiscoveryDocumentAndLogin()?

It sends every visitor straight to Keycloak when they have no valid token. Use it if the whole app requires a login; loadDiscoveryDocumentAndTryLogin(), used here, only finishes a login that is coming back and leaves the login button to the user.

Does the library still use an NgModule?

No. provideOAuthClient is its standalone API. OAuthModule.forRoot() still exists and calls the same providers, for apps that still use NgModules.

Sources

On this page