Skip to content

BFF Authentication Architecture

Status: Draft for Review
System: Angular + Spring Boot 3.4.1 (Java 21) + Auth0
Date: June 2026
Driver: ISO 27001 Certification
Author: skyledge Engineering


Table of Contents

  1. Problem Statement & Solution
  2. System Actors
  3. Current vs Target State
  4. Login Flow
  5. Token Refresh Flow
  6. Security Controls
  7. Attack Scenarios
  8. Production Checklist
  9. Migration Plan

1. Problem Statement & Solution

The Angular frontend currently calls Auth0 directly and stores access_token and refresh_token in browser localStorage. Any JavaScript executing on the page — including scripts injected via XSS — can read these tokens, exfiltrate them, and impersonate the user indefinitely. This is a blocker for ISO 27001 certification.

Core principle of the new design: Tokens never leave the server. The browser receives only an opaque, HttpOnly SESSION cookie. Angular is completely unaware of tokens — it calls BFF endpoints and the BFF injects credentials transparently.

The implementation uses Spring Boot’s OAuth2 client library (spring-boot-starter-oauth2-client) to handle the PKCE generation, state management, token exchange, and JWT validation. The only hand-written auth code is SessionTokenRelayFilter (~40 lines) and BffController.me() (~10 lines).

Key Properties

Property Description
Token isolation Access and refresh tokens stored in the server-side HTTP session, persisted to the database by spring-session-jdbc. Never in any browser context.
HttpOnly session cookie SESSION cookie is JavaScript-inaccessible. XSS payloads cannot read it. Browser sends it automatically on every same-origin request.
Server-side Auth0 handshake The entire OAuth flow — PKCE, state, token exchange — is handled by Spring Security filters. Angular navigates to a BFF URL and waits for a redirect back.
Transparent proxy Angular calls /api/* as usual. SessionTokenRelayFilter intercepts, loads the OAuth2 client from session, and injects Authorization: Bearer server-side before forwarding.

2. System Actors

Note: The BFF and Spring API are the same Spring Boot application running on port 8080. They are separated by two SecurityFilterChain beans in SecurityConfig — Chain 1 claims /bff/**, Chain 2 handles /api/** and all other paths.

Actor Port Role Trust Level
Angular SPA :4200 Frontend application. Navigates to BFF endpoints for auth. Never sees tokens. Sends requests with session cookie auto-attached by browser. Partial trust
Browser — Follows redirects, stores and sends cookies. Enforces HttpOnly and SameSite constraints. The network between browser and BFF is not trusted. Untrusted channel
Spring Boot App :8080 BFF + API in a single process. Chain 1 (/bff/**): owns the OAuth2 login flow via Spring Security filters and exposes /bff/me. Chain 2 (/api/**): SessionTokenRelayFilter injects the Bearer token; BearerTokenAuthenticationFilter validates it before reaching controllers. Fully trusted
Auth0 SaaS — Identity provider. Issues RSA-signed JWTs. Exposes /authorize, /oauth/token, and /.well-known/jwks.json. Validates PKCE and redirect URI allowlists. Trusted IdP

3. Current vs Target State

Before — Vulnerable

Angular SDK → Auth0 /authorize
Auth0 → redirect with access_token + refresh_token
Angular SDK → writes tokens to localStorage
API calls → Angular reads from localStorage, adds Authorization: Bearer

Risks:

  • XSS payload reads localStorage and exfiltrates tokens
  • Tokens visible in browser DevTools under Application → Local Storage
  • No server-side session — cannot revoke a stolen token before expiry
  • Third-party scripts (analytics, ads) share the same origin and can read tokens
  • Auth0 SDK bundled in frontend — client_secret cannot be used safely (public client)

After — Target

Angular → navigate to /bff/authorize/auth0-mock
OAuth2AuthorizationRequestRedirectFilter (Chain 1)
→ generates PKCE + state, stores in session (Spring Session JDBC)
→ redirects browser to Auth0 /authorize
Auth0 → redirects back to /bff/callback with code + state
OAuth2LoginAuthenticationFilter (Chain 1)
→ validates state, exchanges code for tokens (server-to-server)
→ NimbusJwtDecoder validates JWT via JWKS
→ stores OAuth2AuthorizedClient in session (Spring Session JDBC)
→ sets SESSION cookie (HttpOnly, SameSite=Lax)
→ redirects browser to Angular
Angular → GET /bff/me → { userId, email, firstName, lastName, organization }
API calls → Angular calls /api/* normally
SessionTokenRelayFilter (Chain 2)
→ loads OAuth2AuthorizedClient from session
→ refreshes token if expired (via OAuth2AuthorizedClientManager)
→ injects Authorization: Bearer server-side

Properties gained:

  • Tokens never reach the browser — XSS cannot steal what isn’t there
  • Session cookie is JavaScript-inaccessible (HttpOnly)
  • Server-side session enables instant revocation
  • Confidential client: BFF uses client_secret safely (server-side only)
  • Angular has no Auth0 SDK dependency — simpler frontend build
  • ~60 lines of hand-written auth code total (vs hundreds in v1)

4. Login Flow

Authorization Code + PKCE + State

Eight logical steps from user clicking Login to Angular receiving the authenticated user profile. Spring Security filters handle steps 2–7 internally — no custom controller code for the OAuth flow.

Actors: Angular :4200 | Browser | Spring Boot :8080 | Auth0


Step 1 — Angular → Browser: Navigate to BFF

NAVIGATE window.location.href = '/bff/authorize/auth0-mock'

User clicks Login. Angular performs a full browser navigation — not an XHR or fetch call. Angular generates no OAuth parameters. The registration ID auth0-mock is appended to the base path so OAuth2AuthorizationRequestRedirectFilter can look up the correct client registration from application.yaml.


Step 2 — Browser → BFF: GET /bff/authorize/auth0-mock

Handled by OAuth2AuthorizationRequestRedirectFilter (Spring Security — no controller).

DefaultOAuth2AuthorizationRequestResolver generates all PKCE and CSRF parameters automatically via OAuth2AuthorizationRequestCustomizers.withPkce():

Parameter generated Description
code_verifier 32 cryptographically random bytes, Base64URL-encoded. Kept secret in the user’s HTTP session. Never sent to Auth0 at this step — only its hash is.
code_challenge BASE64URL(SHA-256(code_verifier)). Sent to Auth0 so it can validate the exchange later without knowing the secret.
state SecureRandom-generated value. Auth0 echoes it back in the callback. The filter compares the returned value — mismatch means a forged or replayed callback.

The entire OAuth2AuthorizationRequest object (including state, codeVerifier, codeChallenge, redirectUri) is stored in HttpSessionOAuth2AuthorizationRequestRepository — inside the user’s own HTTP session, persisted to PostgreSQL by spring-session-jdbc.

Session storage vs v1 Caffeine cache: Each browser’s pending auth state lives in its own session row in the SPRING_SESSION_ATTRIBUTES table. There is no shared in-memory cache that grows across all concurrent logins. Spring Session’s built-in cleanup cron (spring.session.jdbc.cleanup-cron, default: every minute) purges expired session rows automatically.

BFF returns a 302 to Auth0 /authorize.

DoS protection: Pending auth state is per-session, not a shared structure. An attacker flooding /bff/authorize/auth0-mock creates session rows bounded by the servlet container’s session limits and Postgres table space — cleaned up automatically by Spring Session’s scheduled cleanup. (ISO 27002:2022 §8.6)


Step 3 — Browser → Auth0: GET /authorize?response_type=code&code_challenge=…&state=…

Browser follows BFF’s 302 directly to Auth0 (bypasses the Angular proxy). Auth0:

  • Validates redirect_uri against its registered allowlist — rejects with 400 if not registered
  • Stores the code_challenge with the issued authorization code
  • Redirects back with code + state

Open redirect prevention: Auth0 validates redirect_uri ∈ ALLOWED_REDIRECT_URIS before issuing any code. (RFC 6749 §3.1.2.4)


Step 4 — Browser → BFF (via proxy): GET /bff/callback?code=…&state=…

Handled by OAuth2LoginAuthenticationFilter (Spring Security — no controller).

Auth0 redirects the browser to http://localhost:4200/bff/callback (the Angular dev-server proxy port). The proxy forwards to BFF at :8080.

Why through the proxy? BFF’s Set-Cookie response will be scoped to port 4200 — the same origin as Angular — so the SESSION cookie is sent automatically on all subsequent Angular requests.

OAuth2LoginAuthenticationFilter calls authorizationRequestRepository.removeAuthorizationRequest() first, before any downstream call — removing state and code_verifier from the session. If the returned state does not match the stored value, the callback is rejected with 400.

State consumed immediately: Removed before the token exchange call — not after. Prevents state replay on error paths. (RFC 6749 §10.12)


Step 5 — BFF → Auth0: POST /oauth/token

Handled by DefaultAuthorizationCodeTokenResponseClient (Spring Security). Server-to-server exchange — the browser is not involved.

Body parameter Value Purpose
grant_type authorization_code Selects the code exchange grant.
client_id configured in application.yaml Identifies the registered application.
client_secret configured in application.yaml Proves this is the legitimate server-side BFF. Never sent to Angular. Auth0 returns 401 if wrong.
code <UUID> Single-use authorization code from the callback. Auth0 deletes it on first use.
redirect_uri http://localhost:4200/bff/callback Must exactly match the value from step 2. Prevents a stolen code from being exchanged with a different redirect target.
code_verifier retrieved from session Auth0 verifies SHA-256(code_verifier) == code_challenge. An attacker who only intercepted the auth code cannot produce this.

Auth0 returns: { access_token: <RS256 JWT, exp 5 min>, refresh_token: <…> }


Step 6 — BFF internal: Validate JWT

Handled by NimbusJwtDecoder, auto-configured from spring.security.oauth2.client.provider.auth0-mock.jwks-uri. No custom validator code.

  • Fetches Auth0’s JWKS endpoint on first call; public key is cached and rotated automatically
  • Enforces alg == RS256 — rejects alg:none and all other algorithms
  • Verifies RSA signature
  • Validates exp claim
  • Extracts claims (sub, name, email, and any custom claims) to build OAuth2AuthenticationToken

OAuth2LoginAuthenticationFilter stores the OAuth2AuthorizedClient (accessToken, refreshToken, expiry) in HttpSessionOAuth2AuthorizedClientRepository — persisted to the database via spring-session-jdbc. The SecurityContext (authentication) is also saved to the session.

Spring Security sets the session cookie on the response:

Cookie attribute Value Purpose
Cookie name SESSION Spring Session default name. JavaScript-inaccessible.
HttpOnly true XSS payloads cannot read this cookie.
SameSite Lax Cookie not sent on cross-site POST requests. Blocks CSRF on API endpoints.
Secure (prod) true Must be enabled in production — cookie only transmitted over HTTPS. See Production Checklist.

SavedRequestAwareAuthenticationSuccessHandler redirects the browser to http://localhost:4200/.

Database state after this step (PostgreSQL):

SPRING_SESSION — one row per active session (session_id, expiry_time, …)
SPRING_SESSION_ATTRIBUTES — session attributes including:
• SecurityContext (Authentication / user identity)
• OAuth2AuthorizedClient (accessToken, refreshToken, expiry)

Step 8 — Angular → BFF: GET /bff/me

Handled by BffController.me() — hand-written, ~10 lines. Reads @AuthenticationPrincipal from the SecurityContext stored in the session.

Response:

{
"userId": "auth0|abc123",
"email": "user@example.com",
"firstName": "Demo",
"lastName": "User",
"organization": "skyledge"
}

These fields are sourced from custom Auth0 JWT claims injected via an Auth0 Action or Rule. BffController.me() reads them directly from the OAuth2AuthenticationToken claims — no additional API call to Auth0’s /userinfo endpoint is required. The claims must be configured in Auth0 to be included in the ID/access token.

If no session exists (unauthenticated), Spring Security’s authenticationEntryPoint returns 401 directly — Angular treats this as “not logged in” and shows the Login button.


5. Token Refresh Flow

Access tokens expire after 5 minutes. SessionTokenRelayFilter (Chain 2) triggers a transparent refresh via OAuth2AuthorizedClientManager before forwarding API requests. Angular never observes a token expiry event.

Actors: Angular SPA | Spring Boot :8080 | Auth0


Step 1 — Angular calls GET /api/data. Browser attaches SESSION cookie automatically.

Step 2 — Chain 2 receives the request. SessionTokenRelayFilter reads the SecurityContext from the session and loads OAuth2AuthorizedClient from HttpSessionOAuth2AuthorizedClientRepository.

  • If no session / no client found: returns 401 immediately. Angular redirects to /login.

Step 3 — SessionTokenRelayFilter calls OAuth2AuthorizedClientManager.authorize(). The manager checks OAuth2AccessToken.getExpiresAt() against Instant.now().

Step 4 (if expired) — RefreshTokenOAuth2AuthorizedClientProvider calls DefaultRefreshTokenTokenResponseClient:

POST /oauth/token
{ grant_type=refresh_token, client_id, client_secret, refresh_token }

Auth0 returns a new access_token (and optionally a rotated refresh_token). OAuth2AuthorizedClientManager updates HttpSessionOAuth2AuthorizedClientRepository — new token and expiry written to PostgreSQL’s SPRING_SESSION_ATTRIBUTES automatically.

Step 5 — SessionTokenRelayFilter wraps the HttpServletRequest so getHeader("Authorization") returns Bearer <new_access_token>. The original request continues down the filter chain.

Step 6 — BearerTokenAuthenticationFilter (Chain 2) validates the injected Bearer token via NimbusJwtDecoder. Spring API controller (DataController) is reached only if the JWT is valid.

Step 7 — BFF forwards the Spring API response back to Angular unchanged.


6. Security Controls

Threat Attack Vector Severity Control Implementation
Token theft via XSS Script reads localStorage / sessionStorage HIGH HttpOnly SESSION cookie Tokens stored in SPRING_SESSION_ATTRIBUTES only. Cookie is JS-inaccessible.
Auth code interception Attacker steals code from redirect URL via network sniff, leaked log, or Referer header HIGH PKCE (S256) OAuth2AuthorizationRequestCustomizers.withPkce(). code_verifier stays in session. Code alone is useless.
Login CSRF Attacker forces victim to complete attacker’s auth callback — victim logs into attacker’s account HIGH State parameter OAuth2LoginAuthenticationFilter validates state against session before any token call.
JWT forgery / alg confusion Crafted JWT with modified claims or alg: none HIGH JWKS validation (RS256 only) NimbusJwtDecoder fetches public key from jwks-uri, verifies RSA signature, rejects non-RS256.
CSRF on API calls Malicious site makes cross-origin POST to trigger state changes MED SameSite=Lax Configured in application.yaml. Cookie not sent on cross-site POST requests.
Auth code replay Reuse an intercepted code after initial exchange MED Single-use codes Auth0 deletes the code on first redemption. Second use returns 400 invalid_grant.
Open redirect Manipulate redirect_uri to deliver auth code to attacker’s server HIGH redirect_uri allowlist Auth0 validates against pre-registered URIs before issuing any code.
Pending auth state DoS Flood /bff/authorize/auth0-mock to exhaust resources MED Per-session storage + Spring Session cleanup State lives in each browser’s own session row. Spring Session cleanup cron deletes expired rows every minute.
State replay Resubmit a consumed state value on error paths MED Consume-first pattern authorizationRequestRepository.removeAuthorizationRequest() is called before token exchange on all code paths.
Client impersonation Public caller uses client_id alone to exchange codes HIGH client_secret (confidential client) BFF sends client_secret on token exchange via DefaultAuthorizationCodeTokenResponseClient. Never sent to Angular.

7. Attack Scenarios

These two mechanisms protect different attack vectors. Removing either one leaves a real, exploitable hole — even with the other in place.

Attack 1 — Authorization Code Interception (mitigated by PKCE)

Without PKCE — Stolen code → full account compromise

Auth0 issues a code and redirects the browser. An attacker intercepts the code in transit — via network sniffing, a browser extension, a leaked Referer header, or a compromised proxy.

  1. Attacker sends the code to Auth0’s /oauth/token with their own credentials
  2. Auth0 only checks: is this a valid, unused code + correct credentials?
  3. Auth0 issues access and refresh tokens to the attacker
  4. Victim’s session is now owned by the attacker

With PKCE (S256) — Stolen code is worthless without the verifier

DefaultOAuth2AuthorizationRequestResolver generates a random code_verifier (via withPkce()) and sends only SHA-256(code_verifier) to Auth0. The verifier stays in SPRING_SESSION_ATTRIBUTES — never transmitted.

  1. Attacker intercepts the code — same as before
  2. Attacker sends the code to /oauth/token but cannot produce code_verifier
  3. DefaultAuthorizationCodeTokenResponseClient sends the verifier; Auth0 recomputes the hash and compares — mismatch → 400 invalid_grant
  4. Code exchange rejected. Attacker gets nothing.

Attack 2 — Login CSRF (mitigated by State parameter)

Without State — Victim silently logged into attacker’s account

Attacker logs in to the app as themselves, captures their own auth code from the redirect URL, and stops before completing the callback.

  1. Attacker crafts a link: /bff/callback?code=ATTACKER_CODE
  2. Sends link to victim via email, ad, or hidden iframe
  3. Victim’s browser hits the callback; BFF has no state to compare — accepts blindly
  4. BFF exchanges ATTACKER_CODE and binds the attacker’s identity to the victim’s session cookie
  5. Victim is now logged into the attacker’s account — any data they upload goes to the attacker

With State — Forged callback detected before any token call

When the victim’s request hits /bff/authorize/auth0-mock, OAuth2AuthorizationRequestRedirectFilter generates a random state value and stores it in HttpSessionOAuth2AuthorizationRequestRepository tied to that session.

  1. Attacker’s forged callback carries a foreign state value (or no state)
  2. OAuth2LoginAuthenticationFilter calls removeAuthorizationRequest() — state not found in this session
  3. Filter rejects with 400 before making any call to Auth0
  4. ATTACKER_CODE is never exchanged. Victim’s session untouched.

Note: PKCE and State protect orthogonal attacks. PKCE defends the code itself — it binds the code to the party that generated the verifier. State defends the callback endpoint — it proves the callback was triggered by a flow this BFF instance started. Both must be present.


8. Production Checklist

Items required before go-live. The PoC runs on localhost with H2 and without HTTPS.

  • Add Secure flag to the SESSION cookie (server.servlet.session.cookie.secure=true). Without this, the cookie is transmitted over HTTP — allowing network interception.
  • Confirm the PostgreSQL datasource (spring.datasource.*) and Spring Session JDBC cleanup cron are correctly configured for production load. spring-session-jdbc auto-creates SPRING_SESSION and SPRING_SESSION_ATTRIBUTES on startup when initialize-schema: always is set — switch to never and run DDL manually in strict environments.
  • Confirm SameSite=Lax is sufficient for production. If Angular is served from a different subdomain than the BFF, evaluate SameSite=None; Secure and re-assess CSRF exposure.
  • Restrict the Auth0 tenant’s Allowed Callback URLs to production origins only. Remove localhost:4200 from the production tenant’s allowlist.
  • Confirm the Auth0 tenant rejects code_challenge_method=plain. Only S256 provides meaningful PKCE protection. This is an Auth0 Application setting.
  • Configure Auth0 refresh token rotation and set an absolute refresh token lifetime. Without a lifetime cap, a stolen refresh token is valid indefinitely.
  • Verify the Spring Security logout handler at POST /bff/logout is tested end-to-end: it must invalidate the session (deleting rows from SPRING_SESSION), clear the SESSION cookie, and redirect to Angular.
  • Configure spring.session.jdbc.cleanup-cron for the expected session volume. The default (0 * * * * * — every minute) may be aggressive for high-traffic deployments.
  • Move client_id / client_secret out of application.yaml into environment variables or a secrets manager (AWS Secrets Manager, HashiCorp Vault, etc.).
  • Enable Spring Security DEBUG logging in staging to verify the OAuth2 filter chain behaviour before production rollout: logging.level.org.springframework.security: DEBUG.

Session Schema (PostgreSQL)

spring-session-jdbc auto-creates these two tables on startup when spring.session.jdbc.initialize-schema=always is set:

-- Spring Session creates these automatically:
SPRING_SESSION -- one row per active session
-- columns: session_id, creation_time, last_access_time,
-- max_inactive_interval, expiry_time, principal_name
SPRING_SESSION_ATTRIBUTES -- one row per session attribute
-- covers: SecurityContext, OAuth2AuthorizedClient (tokens),
-- OAuth2AuthorizationRequest (pending PKCE + state)

For strict production environments, set initialize-schema: never and run the DDL manually from the Spring Session JDBC JAR.


9. Migration Plan

Designed to be non-breaking at each phase boundary. The existing auth path can run in parallel until Angular is switched over in Phase 2.

Phase 1 — Deploy BFF Endpoints

No impact on existing Angular auth

  • Add spring-boot-starter-oauth2-client, spring-boot-starter-oauth2-resource-server, spring-session-jdbc to pom.xml
  • Write SecurityConfig.java with two SecurityFilterChain beans — Chain 1 (/bff/**) with oauth2Login + PKCE customizer, Chain 2 (/api/**) with oauth2ResourceServer
  • Write SessionTokenRelayFilter.java (~40 lines) — load OAuth2AuthorizedClient from session, call OAuth2AuthorizedClientManager.authorize(), wrap request with Bearer header, return 401 if no session
  • Write BffController.java — GET /bff/me only (~10 lines), reads @AuthenticationPrincipal
  • Configure application.yaml: Auth0 client registration, provider URIs, session cookie name (SESSION), session store type (jdbc)
  • Deploy behind a feature flag — BFF routes exist but Angular does not use them yet

Phase 2 — Migrate Angular to BFF Auth

The cutover — both paths briefly coexist

  • Replace Auth0 SDK login call with window.location.href = '/bff/authorize/auth0-mock'
  • Replace auth state reads with GET /bff/me — response now returns { userId, email, firstName, lastName, organization }
  • Remove all manual Authorization: Bearer header injection from Angular HTTP interceptors — SessionTokenRelayFilter handles this server-side
  • Update logout to call POST /bff/logout
  • Run integration tests covering: login → /bff/me → API call → token refresh → logout

Phase 3 — Remove Legacy Auth Code

Cleanup — eliminate the vulnerable surface

  • Remove Auth0 Angular SDK (@auth0/auth0-angular) from package.json
  • Delete all localStorage.setItem/getItem calls related to tokens
  • Audit Angular codebase for remaining token handling — grep for access_token, refresh_token, Bearer
  • Remove feature flag — BFF is now the only auth path

Phase 4 — Production Hardening

Before live traffic — complete the checklist above

  • Switch datasource to PostgreSQL; set Secure cookie flag
  • Move client_id / client_secret to secrets manager
  • Restrict Auth0 production tenant callback allowlist to production URLs only
  • Enable Auth0 refresh token rotation and set absolute token lifetime
  • Verify Spring Session JDBC cleanup cron configuration for expected session volume
  • Conduct security review: confirm no token ever appears in response bodies, logs, or error messages

Appendix — Spring Security Component Map

OAuth2 concern Spring Security component Configured by
PKCE generation (code_verifier, code_challenge, S256) OAuth2AuthorizationRequestCustomizers.withPkce() SecurityConfig
Pending auth state storage (state + code_verifier) HttpSessionOAuth2AuthorizationRequestRepository auto-wired
Authorization redirect (/bff/authorize/auth0-mock) OAuth2AuthorizationRequestRedirectFilter Chain 1 oauth2Login config
Callback handling + state validation + code exchange OAuth2LoginAuthenticationFilter Chain 1 oauth2Login config
Token exchange POST to Auth0 DefaultAuthorizationCodeTokenResponseClient auto-configured
JWT validation (JWKS fetch, RS256, expiry) — BFF side NimbusJwtDecoder via OidcIdTokenDecoderFactory spring.security.oauth2.client.provider.*.jwks-uri
JWT validation — API side NimbusJwtDecoder via oauth2ResourceServer spring.security.oauth2.resourceserver.jwt.jwks-uri
Token + session storage HttpSessionOAuth2AuthorizedClientRepository + spring-session-jdbc auto-configured
Token refresh RefreshTokenOAuth2AuthorizedClientProvider via OAuth2AuthorizedClientManager SecurityConfig bean
Bearer token injection SessionTokenRelayFilter hand-rolled (~40 lines)
User profile endpoint BffController.me() hand-rolled (~10 lines)
Logout Spring Security logout handler Chain 1 logout config
Session expiry cleanup Spring Session JDBC cleanup cron spring.session.jdbc.cleanup-cron

Document references: Login flow diagram · Token refresh diagram · PKCE attack comparison · State attack comparison