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
impersonationrole can impersonate ANY user in the realm - A compromised
TOKEN_EXCHANGE_CLIENT_SECRETcould 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:
- On 401 response, frontend tries to open popup immediately (may work if user just clicked Teams icon)
- If popup is blocked, show "Login" button - user click guarantees popup can open
- SSO: If user has active Keycloak session, popup opens and closes almost instantly
- Tokens stored in HTTP-only cookies (not accessible to JavaScript)
- 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
Navigate to Clients in your Keycloak realm
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!)
- Client ID:
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)
- Valid redirect URIs:
In the Credentials tab:
- Copy the Client Secret - you'll need this for
TOKEN_EXCHANGE_CLIENT_SECRET
- Copy the Client Secret - you'll need this for
2. Configure Client Scopes
Teams requires the following scopes for App Suite Middleware access:
openid- Required for OIDC protocolread_mail- Read mail dataread_mailaccount- Read mail account information
These are the default scopes requested. To configure in Keycloak:
- Navigate to Client Scopes
- Create
read_mailandread_mailaccountscopes if they don't exist - 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
impersonationroleview-usersrole
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.comConfiguration Notes
| Variable | Required | Description |
|---|---|---|
AUTH_MODE | Yes | Must be popup to enable this mode |
TOKEN_EXCHANGE_ISSUER_URL | Yes | Keycloak realm URL (no trailing slash) |
TOKEN_EXCHANGE_CLIENT_ID | Yes | Client ID from Keycloak |
TOKEN_EXCHANGE_CLIENT_SECRET | Yes | Client secret from Keycloak |
AUTH_CALLBACK_URI | No | Override callback URI if needed |
AUTH_SCOPES | No | OAuth scopes (default: openid read_mail read_mailaccount) |
ISSUER_ALLOWLIST | Yes | For validating Switchboard tokens in hybrid setups |
Authentication Architecture
Two-Token Model
In popup mode, authentication uses two separate tokens for different purposes:
| Token | Purpose | Source | Transport |
|---|---|---|---|
| Switchboard JWT | User identity (userId, contextId, scope) | Switchboard (existing App Suite auth) | Authorization header |
| Keycloak Token | API calls to Java Middleware | Keycloak (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:
| Storage | Contents | Location |
|---|---|---|
Cookie teams_sid | Session ID (UUID) | Browser (HttpOnly, Secure, SameSite=Lax) |
Database sessions table | Keycloak access/refresh tokens, expiry | PostgreSQL |
Database auth_state table | PKCE 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:
- Frontend request returns 401
- Frontend calls
POST /api/auth/refresh - Backend uses refresh token to get new access token from Keycloak
- New tokens stored in cookies
- 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
Popup Behavior
User Experience
The popup is designed for minimal disruption:
- With SSO session: Popup opens, authenticates instantly, closes - often so fast user barely notices
- Without SSO session: Popup shows Keycloak login form, user authenticates, popup closes
- 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
Popup Window Specifications
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:
| Endpoint | Method | Description |
|---|---|---|
/api/auth/login | GET | Returns { authUrl } for initiating auth |
/api/auth/callback | GET | OIDC callback - exchanges code for tokens |
/api/auth/refresh | POST | Refreshes access token using refresh token |
/api/auth/logout | POST | Clears 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
- Open Teams application in browser
- Open browser developer tools (Network tab)
- 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 consoleExpected 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
Popup is Always Blocked
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:
- Check
AUTH_CALLBACK_URIenvironment variable - Verify Keycloak client has correct Valid redirect URIs
- Ensure protocol (http/https) matches exactly
Error: "Invalid client credentials"
Cause: Client secret mismatch.
Solution:
- Verify
TOKEN_EXCHANGE_CLIENT_SECRETmatches Keycloak - Regenerate secret in Keycloak if needed
- Ensure client has Client authentication enabled
Error: "Session expired" or "PKCE code verifier mismatch"
Cause: Auth state expired or was already consumed.
Solution:
- Auth state expires after 10 minutes - complete login flow promptly
- Auth state is single-use - each login attempt needs a fresh
/api/auth/logincall - Verify database connectivity (auth state stored in
auth_statetable)
Refresh Token Fails
Cause: Refresh token expired or revoked.
Solution:
- User will see login button - this is expected behavior
- Increase refresh token lifetime in Keycloak if sessions expire too quickly
- Check Keycloak session settings
CORS Errors
Cause: Web origins not configured in Keycloak.
Solution:
- In Keycloak client settings, add your domain to Web origins
- Alternatively, set to
+to allow all redirect URI origins
Comparison: Auth Code Flow vs Token Exchange
| Aspect | Auth Code Flow (Popup) | Token Exchange |
|---|---|---|
| User authentication | Direct with Keycloak | Via Switchboard |
| Impersonation role | Not required | Required |
| Shared realm risk | Low (no impersonation) | High (realm-wide impersonation) |
| Secret compromise impact | Teams only | All realm users |
| User experience | Popup (SSO = instant) | Seamless (already authenticated) |
| Configuration | Simpler (no impersonation) | More complex |
| Keycloak features | Standard OIDC | token-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

