Skip to content

Add OIDC Authorization Code Flow for Direct User Authentication

  • Deciders: Julian Bäume
  • Date: 2025-12-18

Status

Accepted

Context

Security Problem with Token Exchange + Impersonation

The current token exchange mode (ADR-0011) grants the Teams service account the impersonation role in Keycloak. This creates a significant security risk when the Keycloak realm is shared with other applications:

  1. Scope of Access: A compromised OPENID_CLIENT_SECRET allows impersonation of ANY user in the entire Keycloak realm
  2. Shared Realm Risk: When Keycloak hosts multiple applications (HR systems, chat, payroll, etc.), a Teams compromise exposes ALL applications
  3. Blast Radius: The attack surface extends far beyond Teams' legitimate need to access App Suite Middleware

With a compromised client secret, an attacker can:

# Get service account token
SERVICE_TOKEN=$(curl -s -X POST "$KEYCLOAK_URL/token" \
  -d "client_id=teams" \
  -d "client_secret=STOLEN_SECRET" \
  -d "grant_type=client_credentials" | jq -r '.access_token')

# Impersonate ANY user for ANY audience in the realm
curl -X POST "$KEYCLOAK_URL/token" \
  -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
  -d "subject_token=$SERVICE_TOKEN" \
  -d "requested_subject=admin@1" \
  -d "audience=hr-system"  # Access HR, not just Teams!

Keycloak Limitations

We investigated whether Keycloak 26.2's Client Policies could restrict token exchange to specific audiences. The findings:

  • Client Policies for audience restriction are planned (keycloak#38317) but not yet implemented
  • Fine-grained permissions on target clients can deny specific clients, but must be configured per-client and new clients are unprotected by default
  • Impersonation with requested_subject requires the legacy token-exchange (V1) feature, which has limited security controls

Proposed Solution: OIDC Authorization Code Flow

Instead of impersonating users server-side, have users authenticate directly with Keycloak via browser popup:

  1. User's browser opens Keycloak authorization endpoint in popup
  2. User authenticates (or SSO kicks in if session exists)
  3. Keycloak redirects to Teams callback with authorization code
  4. Backend exchanges code for tokens (access + refresh)
  5. Tokens stored server-side in PostgreSQL, only session ID in HTTP-only cookie
  6. Refresh tokens used to renew sessions transparently

Key security benefit: No impersonation role needed. Even if client secret is compromised, attacker cannot impersonate users.

Two-Token Authentication Model

In popup mode, authentication uses two separate tokens for different purposes:

TokenPurposeSourceTransport
Switchboard JWTUser identity (userId, contextId, scope)Switchboard (existing App Suite auth)Authorization header
Keycloak TokenAPI calls to Java MiddlewareKeycloak (via popup flow)Server-side session

This separation provides clear security boundaries:

  • Switchboard JWT: Identifies the user to Teams (same as non-popup modes)
  • Keycloak Token: Used only for MW communication, never sent to browser

Decision

Implement OIDC Authorization Code Flow as a third authentication mode (AUTH_MODE=popup), alongside the existing token-exchange and Switchboard legacy modes.

Why Popup (not full redirect)?

  • Teams runs as a microfrontend inside App Suite
  • Full-page redirect would disrupt App Suite session and navigation state
  • Popup allows authentication without losing application context
  • Popup can close immediately if Keycloak session exists (SSO)

Why Not Iframe?

  • Many IdPs block iframe embedding via X-Frame-Options
  • Keycloak defaults to blocking iframe authentication
  • Security concerns with clickjacking attacks
  • Popup is the standard approach for embedded applications

User Interaction Flow

Browsers block popups not triggered by user interaction. The implementation handles this:

  1. First API request returns 401 with auth URL
  2. Try to open popup immediately (may work if user just clicked Teams icon)
  3. If popup blocked, show "Login" button
  4. User clicks button → popup opens (guaranteed with user interaction)
  5. After auth, popup posts message and closes
  6. Original request is retried with new token

Server-Side Session Storage

Keycloak tokens are stored server-side in PostgreSQL, not in browser cookies:

StorageContentsLocation
Cookie teams_sidSession ID (UUID)Browser (HttpOnly, Secure, SameSite=Lax)
Database sessions tableKeycloak access/refresh tokens, expiryPostgreSQL
Database auth_state tablePKCE state (temporary, consumed after use)PostgreSQL

Security benefits:

  • Tokens never reach browser: Immune to XSS attacks
  • Horizontal scaling: Session data in database allows multiple server instances
  • Small cookie size: Session ID is ~36 bytes, well under browser limits
  • PKCE in database: Enables stateless servers while maintaining security

Consequences

Positive

  • Eliminated Impersonation Risk: No service account can impersonate users
  • Scoped Access: Compromised secret only affects Teams client, not entire realm
  • User Consent: Users authenticate directly with Keycloak
  • Standard Flow: Authorization Code + PKCE is OAuth 2.0 best practice
  • Refresh Tokens: Longer sessions without re-authentication
  • Audit Trail: All authentications logged as standard auth events

Negative

  • Popup UX: Users may have popup blockers (handled with fallback button)
  • Initial Auth Required: First access requires popup interaction
  • Session Management: Must handle token refresh and expiry
  • Complexity: Third authentication mode adds code paths
  • SSO Dependency: Best experience requires existing Keycloak session

Security Comparison

AspectToken Exchange (ADR-0011)Auth Code Flow (this ADR)
Compromised Secret ImpactAny user in realmOnly Teams client
Service Account Rolesimpersonation, view-usersNone required
User InteractionNonePopup (once per session)
Cross-Realm AccessAny audienceOnly Teams
Audit TrailToken exchange eventsStandard auth events

Keycloak Configuration

For popup mode, the Teams client needs:

  • Standard Flow Enabled: ON
  • Client Authentication: ON (confidential)
  • Valid Redirect URIs: Callback URL
  • Service Accounts Roles: OFF (not needed)
  • NO impersonation role - this is the security benefit

References