Skip to content

OIDC Authorization Code Flow Setup for App Suite Teams

This document explains how to configure Keycloak and Teams to use OIDC Authorization Code Flow for authentication. This is a popup-based authentication mode where users authenticate directly with Keycloak.

Overview

In this mode, users authenticate directly with Keycloak via a browser popup. The Teams service acts as a standard OIDC Relying Party (client), not an impersonating service. This provides stronger security isolation when the Keycloak realm is shared with other applications.

Security Motivation

When the same Keycloak realm hosts multiple applications (HR systems, chat platforms, etc.), the token exchange with impersonation mode presents a security concern:

  • A service account with impersonation role can impersonate ANY user in the realm
  • A compromised TOKEN_EXCHANGE_CLIENT_SECRET could allow attackers to impersonate users for ALL applications in the realm

With Authorization Code Flow:

  • Users authenticate directly with Keycloak
  • No impersonation role is required
  • A compromised client secret only affects the Teams application, not user impersonation across the realm

See ADR-0014 for detailed architectural context.

Authentication Flow

Key points:

  1. On 401 response, frontend tries to open popup immediately (may work if user just clicked Teams icon)
  2. If popup is blocked, show "Login" button - user click guarantees popup can open
  3. SSO: If user has active Keycloak session, popup opens and closes almost instantly
  4. Tokens stored in HTTP-only cookies (not accessible to JavaScript)
  5. Frontend retries original request after successful authentication

Requirements

  • Keycloak 18.x or later (tested with Keycloak 26.2)
  • Admin access to Keycloak realm configuration
  • No special feature flags required (unlike token exchange mode)

Keycloak Configuration

1. Create or Configure the Teams Client

  1. Navigate to Clients in your Keycloak realm

  2. Create a new client or edit existing:

    • Client ID: teams (or your preferred identifier)
    • Client authentication: ON (must be confidential)
    • Standard flow: ON (required for authorization code flow)
    • Direct access grants: OFF (not needed, reduces attack surface)
    • Service accounts roles: OFF (not needed - no impersonation!)
  3. In the Settings tab, configure:

    • Valid redirect URIs: https://your-domain/teams/api/auth/callback
    • Valid post logout redirect URIs: https://your-domain/* (optional)
    • Web origins: https://your-domain (for CORS)
  4. In the Credentials tab:

    • Copy the Client Secret - you'll need this for TOKEN_EXCHANGE_CLIENT_SECRET

2. Configure Client Scopes

Teams requires the following scopes for App Suite Middleware access:

  • openid - Required for OIDC protocol
  • read_mail - Read mail data
  • read_mailaccount - Read mail account information

These are the default scopes requested. To configure in Keycloak:

  1. Navigate to Client Scopes
  2. Create read_mail and read_mailaccount scopes if they don't exist
  3. Assign to Teams client under Client Scopes tab

3. No Impersonation Role Required

Important: Unlike token exchange mode, authorization code flow does NOT require:

  • Service accounts roles
  • impersonation role
  • view-users role

This is the primary security benefit of this authentication mode.

Environment Configuration

Configure the following environment variables for Teams:

# Enable popup auth mode
AUTH_MODE=popup

# Keycloak OIDC Configuration
TOKEN_EXCHANGE_ISSUER_URL=https://your-keycloak-domain/realms/your-realm
TOKEN_EXCHANGE_CLIENT_ID=teams
TOKEN_EXCHANGE_CLIENT_SECRET=your-client-secret-from-keycloak

# Optional: Custom callback URI (defaults to /teams/api/auth/callback)
AUTH_CALLBACK_URI=https://your-domain/teams/api/auth/callback

# Optional: Additional scopes (defaults to "openid read_mail read_mailaccount")
# AUTH_SCOPES=openid read_mail read_mailaccount additional_scope

# Switchboard Token Validation (still required for existing Switchboard flows)
ISSUER_ALLOWLIST=switchboard.example.com

Configuration Notes

VariableRequiredDescription
AUTH_MODEYesMust be popup to enable this mode
TOKEN_EXCHANGE_ISSUER_URLYesKeycloak realm URL (no trailing slash)
TOKEN_EXCHANGE_CLIENT_IDYesClient ID from Keycloak
TOKEN_EXCHANGE_CLIENT_SECRETYesClient secret from Keycloak
AUTH_CALLBACK_URINoOverride callback URI if needed
AUTH_SCOPESNoOAuth scopes (default: openid read_mail read_mailaccount)
ISSUER_ALLOWLISTYesFor validating Switchboard tokens in hybrid setups

Authentication Architecture

Two-Token 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

Server-Side Session Storage

Keycloak tokens are stored server-side in a PostgreSQL database, with only a small session ID in an HTTP-only cookie:

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:

  • Server-side tokens: Keycloak tokens never exposed to browser, immune to XSS
  • No impersonation risk: No service account can impersonate users
  • Horizontal scaling: Session data in database allows multiple server instances
  • Small cookie size: Session ID is ~36 bytes, well under 4KB browser limit

Token Refresh

When the access token expires:

  1. Frontend request returns 401
  2. Frontend calls POST /api/auth/refresh
  3. Backend uses refresh token to get new access token from Keycloak
  4. New tokens stored in cookies
  5. Original request is retried automatically

Session Duration

Session duration is determined by:

  • Access token lifetime: Configured in Keycloak (Realm Settings → Tokens)
  • Refresh token lifetime: Configured in Keycloak (typically longer)
  • SSO session idle: How long until Keycloak SSO session expires

Recommended settings for good UX:

  • Access token: 5 minutes
  • Refresh token: 30 minutes to 8 hours (based on security requirements)
  • SSO session idle: 30 minutes

User Experience

The popup is designed for minimal disruption:

  1. With SSO session: Popup opens, authenticates instantly, closes - often so fast user barely notices
  2. Without SSO session: Popup shows Keycloak login form, user authenticates, popup closes
  3. Popup blocked: Login button appears, user clicks, popup opens (guaranteed to work with direct user interaction)

Browser Compatibility

Popup behavior is consistent across browsers:

  • Chrome/Edge: Popup blocked unless triggered by user interaction (within ~1s)
  • Firefox: Similar behavior, slightly more permissive
  • Safari: Strictest popup blocking, login button may be needed more often
window.open(authUrl, 'teams-auth', 'width=500,height=600,menubar=no,toolbar=no,location=no,status=no')

API Endpoints

The following endpoints are available in popup mode:

EndpointMethodDescription
/api/auth/loginGETReturns { authUrl } for initiating auth
/api/auth/callbackGETOIDC callback - exchanges code for tokens
/api/auth/refreshPOSTRefreshes access token using refresh token
/api/auth/logoutPOSTClears auth tokens

Verification and Testing

1. Verify Configuration

Check that Teams detected popup mode:

# Fetch config endpoint
curl https://your-domain/teams/api/config | jq .auth
# Should return: { "mode": "popup" }

2. Test Login Flow

  1. Open Teams application in browser
  2. Open browser developer tools (Network tab)
  3. Observe:
    • Initial API request returns 401
    • Popup opens (or login button appears)
    • After auth, requests succeed with cookies

3. Verify Token Contents

After authentication, verify session was created:

# Check session cookie exists (in browser console)
document.cookie.split('; ').find(row => row.startsWith('teams_sid'))
# Note: Only session ID is visible, not the actual tokens (stored server-side)

# To inspect tokens, check backend logs or Keycloak admin console

Expected claims:

  • iss: Keycloak realm URL
  • azp: teams (authorized party)
  • sub: User's Keycloak ID
  • email: User's email (if scope included)
  • preferred_username: User's username

Troubleshooting

Symptom: Login button always appears, popup never opens automatically.

Cause: No recent user interaction before auth attempt.

Solution: This is expected browser security behavior. The login button provides the required user interaction.

Error: "Invalid redirect_uri"

Cause: Callback URL doesn't match Keycloak configuration.

Solution:

  1. Check AUTH_CALLBACK_URI environment variable
  2. Verify Keycloak client has correct Valid redirect URIs
  3. Ensure protocol (http/https) matches exactly

Error: "Invalid client credentials"

Cause: Client secret mismatch.

Solution:

  1. Verify TOKEN_EXCHANGE_CLIENT_SECRET matches Keycloak
  2. Regenerate secret in Keycloak if needed
  3. Ensure client has Client authentication enabled

Error: "Session expired" or "PKCE code verifier mismatch"

Cause: Auth state expired or was already consumed.

Solution:

  1. Auth state expires after 10 minutes - complete login flow promptly
  2. Auth state is single-use - each login attempt needs a fresh /api/auth/login call
  3. Verify database connectivity (auth state stored in auth_state table)

Refresh Token Fails

Cause: Refresh token expired or revoked.

Solution:

  1. User will see login button - this is expected behavior
  2. Increase refresh token lifetime in Keycloak if sessions expire too quickly
  3. Check Keycloak session settings

CORS Errors

Cause: Web origins not configured in Keycloak.

Solution:

  1. In Keycloak client settings, add your domain to Web origins
  2. Alternatively, set to + to allow all redirect URI origins

Comparison: Auth Code Flow vs Token Exchange

AspectAuth Code Flow (Popup)Token Exchange
User authenticationDirect with KeycloakVia Switchboard
Impersonation roleNot requiredRequired
Shared realm riskLow (no impersonation)High (realm-wide impersonation)
Secret compromise impactTeams onlyAll realm users
User experiencePopup (SSO = instant)Seamless (already authenticated)
ConfigurationSimpler (no impersonation)More complex
Keycloak featuresStandard OIDCtoken-exchange preview

Recommendation: Use Auth Code Flow when:

  • Keycloak realm is shared with other applications
  • Security isolation is a priority
  • Users already have Keycloak SSO sessions

Use Token Exchange when:

  • Dedicated realm for App Suite
  • Seamless authentication from Switchboard is preferred
  • Legacy compatibility is required

References