Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

MSAL Exchange Handler

The msal-exchange module in light-spa-4j provides a handler to exchange Microsoft Authentication Library (MSAL) tokens for internal application session cookies. This mechanism effectively serves as a Backend-For-Frontend (BFF) authentication layer for Single Page Applications (SPAs).

Core Components

MsalTokenExchangeHandler

This middleware handler intercepts requests to specific paths (configured via msal-exchange.yml) to perform token exchange or logout operations.

  • Token Exchange: Validates the incoming Microsoft Bearer token, performs a token exchange via the OAuth provider, and sets secure, HTTP-only session cookies (accessToken, refreshToken, csrf, etc.) for subsequent requests.
  • Logout: Clears all session cookies to securely log the user out.
  • Session Management: On subsequent requests, it validates the JWT in the cookie, checks for CSRF token consistency, and handles automatic token renewal if the session is nearing expiration.

MsalExchangeConfig

Configuration class that loads settings from msal-exchange.yml. It supports hot reloading and module registration.

Configuration

The module is configured via msal-exchange.yml.

Key Settings:

  • enabled: Enable or disable the handler.
  • exchangePath: Partial path for triggering token exchange (default: /auth/ms/exchange).
  • logoutPath: Partial path for triggering logout (default: /auth/ms/logout).
  • cookieDomain / cookiePath: Scope configuration for the session cookies.
  • cookieSecure: Whether to mark cookies as Secure (HTTPS only).
  • sessionTimeout: Max age for the session cookies.
  • logoutCsrfEnforced: Enforce logout double-submit CSRF after observe-only qualification (default: false).

Example Configuration:

enabled: true
exchangePath: /auth/ms/exchange
logoutPath: /auth/ms/logout
cookieDomain: localhost
cookiePath: /
cookieSecure: false
sessionTimeout: 3600
rememberMeTimeout: 604800
logoutCsrfEnforced: false

HTTP Contract

Token exchange is a bodyless POST to /auth/ms/exchange with the Microsoft token only in Authorization: Bearer .... Logout is a credentialed, bodyless POST to /auth/ms/logout with X-CSRF-TOKEN read from the readable csrf cookie. A zero-length request remains valid when a shared client declares Content-Type: application/json.

Successful logout returns 204 No Content, no response content type or body, and deletion cookies for every cookie name the handler can set. Route OPTIONS explicitly through a chain with CORS before msal-exchange.

Exchange and logout are POST-only. A legacy GET or another unsupported method returns HTTP 405, ERR10008, and Allow: POST before token-server or cookie side effects.