Authentication in a SPA with Keycloak

,
Photo by Patrick Robert Doyle on Unsplash

Single Page Applications (SPAs) require a secure and efficient authentication mechanism to manage user sessions and access control. Keycloak, an open-source Identity and Access Management (IAM) solution, provides a robust way to integrate authentication and authorization in SPAs.

Why Use Keycloak for SPAs?

Keycloak offers features such as Single Sign-On (SSO), social login, role-based access control (RBAC), and token-based authentication using OpenID Connect (OIDC) and OAuth 2.0. This makes it an ideal choice for handling authentication in SPAs.

Backend services called by SPAs use the token acquired from Keycloak to verify the user.

SPA token based authentication with keycloak

How Keycloak Works with SPAs

Keycloak integrates with Single Page Applications (SPAs) using OAuth 2.0 Authorization Code Flow with PKCE (Proof Key for Code Exchange), ensuring secure authentication and authorization. This approach is recommended for SPAs because it removes the need for storing client secrets in the frontend and mitigates risks such as token interception.

The flow is executed in the following way:

Step 1: SPA redirects to Keycloak for authentication

When a user visits the frontend SPA and clicks “Login”, the SPA redirects the user to the Keycloak authorization endpoint in the backend.

Example of the call to Keycloak:

https://{KEYCLOAK_URL}/realms/{REALM}/protocol/openid-connect/auth
?client_id={CLIENT_ID}
&redirect_uri={REDIRECT_URI}
&response_type=code
&scope=openid profile email
&code_challenge={CODE_CHALLENGE}
&code_challenge_method=S256

Parameters:

  • client_id → The Keycloak Client ID assigned to the SPA.
  • redirect_uri → The URL where Keycloak redirects after login.
  • response_type=code → Requests an authorization code.
  • scope=openid profile email → Requests user details.
  • code_challenge → A hashed, random PKCE verifier (prevents code interception).
  • code_challenge_method=S256 → Specifies SHA-256 hashing for PKCE.

Step 2: User logs in via Keycloak

  • The user is redirected to Keycloak’s login page.
  • The user enters their username/password (or uses a social login if configured).
  • If authentication is successful, Keycloak redirects the user back to the SPA with an authorization code:

Example callback URL:

https://your-spa.com/callback?code={AUTH_CODE}&state={STATE}

Step 3: SPA Exchanges Authorization Code for Tokens

Once the SPA receives the authorization code, it sends a POST request to Keycloak’s token endpoint to exchange the authorization code for an access token and refresh token.

Token Exchange Request
POST https://{KEYCLOAK_URL}/realms/{REALM}/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded
client_id={CLIENT_ID}
&grant_type=authorization_code
&code={AUTH_CODE}
&redirect_uri={REDIRECT_URI}
&code_verifier={CODE_VERIFIER}

Parameters:

  • client_id → The SPA client ID.
  • grant_type=authorization_code → Specifies the grant type.
  • code → The authorization code received in Step 2.
  • redirect_uri → Must match the one used in Step 1.
  • code_verifier → The original PKCE random string.

Step 4: Keycloak Responds with Tokens

If the request is valid, Keycloak responds with the following response body:

{
  "access_token": "{ACCESS_TOKEN}",
  "refresh_token": "{REFRESH_TOKEN}",
  "id_token": "{ID_TOKEN}",
  "expires_in": 300
}
  • access_token → Used to make authenticated API requests.
  • refresh_token → Used to obtain new tokens when expired.
  • id_token → Contains user profile details (if openid scope was included).

Step 5: SPA Uses Access Token to Call APIs

Now, the SPA stores the access_token (typically in memory or session storage) and includes it in API requests:

GET /api/user-profile
Authorization: Bearer {ACCESS_TOKEN}

The backend API verifies the token before processing the request.

Implementing Keycloak in a SPA

To integrate Keycloak into an SPA, follow these steps:

  1. Set Up Keycloak:
    • Deploy Keycloak and create a realm.
    • Configure a client for your SPA with the appropriate redirect URIs.
  2. Use a Keycloak JavaScript Adapter:
    • Install Keycloak’s JavaScript adapter for your framework (see below)
    • Initialize Keycloak in your application
  3. Secure API Calls:
    • Include the access token in API requests
  4. Token Refresh Handling:
    • Keycloak’s adapter can refresh tokens automatically

​To integrate Keycloak authentication into your Angular or React applications, you can utilize the following adapters:​

Angular:

  • Keycloak-Angular Adapter: This adapter facilitates the integration of Keycloak with Angular applications, providing features like dependency injection support and easy initialization.​

React:

  • Keycloak JavaScript Adapter (keycloak-js): The official Keycloak JavaScript adapter can be used directly in React applications to manage authentication and authorization.​

Conclusion

Keycloak provides a seamless authentication experience for Single Page Applications by leveraging OAuth 2.0. Using the OAuth2 Authorization Code Flow with PKCE for SPAs ensures security, efficiency, and compliance with modern authentication standards.

With features like token-based security, session management, and role-based access control, Keycloak ensures secure and scalable user authentication. By integrating Keycloak, developers can focus on building their applications while leaving authentication complexities to a reliable IAM solution.

If you want to know more about using Keycloak for your IAM solutions, feel free to contact us.