Keycloak Token Exchange Setup for App Suite Teams
This document explains how to configure Keycloak to use token exchange with impersonation for authenticating the Teams service with App Suite Middleware.
Overview
Teams validates Switchboard-issued tokens locally and uses Keycloak token exchange with impersonation to obtain user-specific JWTs for App Suite Middleware.
Authentication Flow
The following diagram illustrates the token exchange flow:
Flow summary:
- User authenticates via Switchboard, Teams receives a user JWT
- Teams validates the Switchboard token locally (signature and claims verification)
- Teams obtains a service account token from Keycloak (client credentials grant)
- Teams exchanges the service account token for a user token using impersonation
- Teams uses the Keycloak-issued user token with App Suite MW
Requirements
- Keycloak 4.x or later (tested with Keycloak 26.2)
- Admin access to Keycloak realm configuration
- Switchboard JWKS endpoint accessible from Teams
Enable Required Feature Flag
Token exchange with impersonation requires the token-exchange (v1) preview feature flag. While Keycloak 26.2+ includes standard token exchange v2 by default, v2 does not yet support impersonation. The v1 feature has been available as a preview feature since Keycloak 4.x:
# For containerized deployments (environment variable)
KC_FEATURES=token-exchange
# For standalone/development (command line)
kc.sh start-dev --features=token-exchange
# For production deployments (command line)
kc.sh start --features=token-exchangeNote: Without this feature flag, Keycloak will reject the requested_subject parameter with error: Parameter 'requested_subject' is not supported
Keycloak Configuration
1. Create or Configure the Teams Client
Navigate to Clients in your Keycloak realm
Create a new client or edit the existing Teams client:
- Client ID:
teams(or your preferred identifier) - Client authentication: ON (must be confidential)
- Service accounts roles: ON (required for impersonation)
- Client ID:
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
The Teams service explicitly requests the scopes it needs during token exchange. Configure these scopes in Keycloak:
Navigate to Client Scopes
Create scopes if they don't exist:
read_mailaccount- Permission to read mail account informationread_mail- Permission to read mail messages
Assign scopes to the Teams client:
- Navigate to Clients → teams → Client Scopes tab
- Add
read_mailaccountandread_mailas Optional scopes (recommended)
Note: Scopes can also be configured as Default scopes for backward compatibility. When configured as Default, they are always included in tokens regardless of the request. When configured as Optional, they are only included when explicitly requested by the Teams service (which it does).
3. Configure Impersonation Permissions
Assign the Teams service account permission to impersonate users:
- Navigate to Clients → teams → Service account roles tab
- Click Assign role
- Filter by clients: Select realm-management
- Assign the following roles:
impersonation(allows the service to impersonate users)view-users(allows the service to look up user information)
4. Configure Audience for App Suite Middleware (Optional)
The audience parameter in token exchange is optional and only necessary if App Suite MW is explicitly configured to validate the aud claim. By default, App Suite MW validates JWT signatures and issuers, but does not require specific audience claims.
If your App Suite MW deployment validates audience claims:
- Navigate to Clients and find your App Suite MW client (e.g.,
appsuite-mw) - Note the Client ID - this will be used as the audience parameter in Teams configuration
- Ensure the App Suite MW client is configured to validate tokens from this realm
If you're unsure whether audience validation is configured, you can safely omit the AUDIENCE environment variable in Teams - tokens will still work as long as signature and issuer validation passes.
5. Create a Client Scope for User Identity Mapping
App Suite MW uses the login claim to derive both user and context information. The standard MW configuration is:
com.openexchange.oauth.provider.userLookupClaim: login
com.openexchange.oauth.provider.contextLookupClaim: loginCreate a protocol mapper to include the required login claim in exchanged tokens:
Navigate to Client Scopes → Create new scope:
- Name:
appsuite-user-identity - Protocol:
openid-connect
- Name:
Add mapper for login claim (REQUIRED):
- Mapper Type:
User Attribute(Important: Must be "User Attribute", not other mapper types) - Name:
login-mapper(display name, can be any descriptive name) - User Attribute:
appsuite-login(or whatever attribute name you choose for your users - must match your user provisioning) - Token Claim Name:
login(this is what App Suite MW expects) - Claim JSON Type:
String - Add to access token: ON
Note: The User Attribute field must match the attribute name on your Keycloak users. Use
appsuite-loginif using the dynamic user provider extension (Approach 2).- Mapper Type:
Optional: Add additional mappers for debugging/logging
These mappers are not used by MW but can be helpful for troubleshooting:
userId mapper (optional):
- Mapper Type:
User Property - Name:
userId - Property:
username - Token Claim Name:
userId - Add to access token: ON
- Mapper Type:
contextId mapper (optional):
- Mapper Type:
User Attribute - Name:
contextId - User Attribute:
contextId - Token Claim Name:
contextId - Add to access token: ON
- Mapper Type:
Assign this scope to the Teams client as a default scope
Important: The login mapper must be a User Attribute mapper for token exchange to work correctly. Other mapper types may not include the claim in exchanged tokens.
6. User Identity Mapping
For impersonation to work, users must exist in Keycloak when Teams requests token exchange. There are two approaches depending on your environment:
Approach 1: Static User Provisioning (Production)
Users are pre-provisioned in Keycloak (via LDAP, user federation, manual creation, or import). This is the recommended approach for production environments.
Requirements:
Username Matching: The
requested_subjectsent by Teams must match a username in Keycloak- Example: If Teams sends
requested_subject: "alice@12345", a Keycloak user with usernamealice@12345must exist
- Example: If Teams sends
User Attribute for Login Claim: Each user needs an attribute in format
userLocalPart@contextId- Attribute name is configurable - choose a name when creating your mapper (step 5)
- Value format:
localpart@contextId(e.g.,alice@12345) - To configure: Navigate to Users → select user → Attributes tab → Add attribute
Mapper Configuration Alignment: Ensure your mapper's User Attribute field (step 5) matches your chosen attribute name
Bulk provisioning: Use LDAP, Active Directory, Keycloak Admin API, or CSV import.
Approach 2: Dynamic User Creation (Development/Testing)
Users are created on-the-fly during token exchange using a Keycloak User Storage Provider extension. Ideal for development and testing environments where users change frequently.
When Teams requests requested_subject: "alice@12345", the extension automatically creates a user with the appsuite-login attribute set correctly.
Setup: See keycloak-extensions/app-suite-dynamic-users/README.md in the repository root for installation and configuration.
Security: Configure the extension to only allow specific client IDs (e.g., as-teams).
Token Exchange Protocol Details
The token exchange request follows RFC 8693 format:
POST /realms/{realm}/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded
grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&subject_token={service-account-token}
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&requested_subject={user-identity-from-switchboard}
&requested_token_type=urn:ietf:params:oauth:token-type:access_token
&scope=read_mail read_mailaccount
&audience={appsuite-mw-client-id}Key parameters:
subject_token: Teams' service account token (obtained via client credentials grant)requested_subject: User identity extracted from validated Switchboard tokenscope: Explicitly requested scopes (space-delimited) - Teams requestsread_mail read_mailaccountaudience: App Suite MW client ID for token scoping (optional)
Switchboard Token Validation
Before requesting impersonation, Teams validates Switchboard tokens locally by fetching public keys from https://{ISSUER_ALLOWLIST}/.well-known/jwks.json, verifying signatures, validating claims, and extracting the user identity for requested_subject. This validation happens entirely in Teams without Keycloak involvement.
Configuration
Environment Variables
Configure the following environment variables for Teams:
# User JWT Validation (Core UI issuer allowlist)
ISSUER_ALLOWLIST=switchboard.example.com
# Token Exchange Configuration (Keycloak)
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: Audience for App Suite MW
AUDIENCE=appsuite-mw
# Optional: Template for requested_subject (see below)
REQUESTED_SUBJECT_TEMPLATE=${local}@${contextId}Notes:
ISSUER_ALLOWLIST- Comma-separated list of allowed JWT issuers for user token validation (supports wildcards like*.example.com)TOKEN_EXCHANGE_ISSUER_URL- Full Keycloak realm URL (no trailing slash). When set, enables token exchange mode; when not set, Teams uses legacy Switchboard authentication.TOKEN_EXCHANGE_CLIENT_SECRET- From Teams client's Credentials tab in KeycloakAUDIENCE- (Optional) App Suite MW client ID. Only required if your MW deployment validates theaudclaim. Omit if unsure - tokens work without it if MW doesn't check audience.REQUESTED_SUBJECT_TEMPLATE- (Optional) Template for constructing therequested_subjectparameter. See Requested Subject Template below.
Helm Values
For Kubernetes deployments with Helm, configure token exchange in your values file:
# User JWT validation
oidc:
issuer: switchboard.example.com
# Token Exchange configuration
tokenExchange:
enabled: true
issuerUrl: https://your-keycloak-domain/realms/your-realm
clientId: teams
# Option 1: Direct secret (not recommended for production)
clientSecret: your-client-secret-from-keycloak
# Option 2: Use existing secret (recommended)
existingSecret: keycloak-client-secret
clientSecretKey: client-secret # Key in existing secretRecommended: Use Existing Secrets
For production deployments, use external secret management tools (External Secrets Operator, cert-manager, Sealed Secrets, etc.) to create secrets, then reference them:
tokenExchange:
enabled: true
issuerUrl: https://keycloak.example.com/realms/ox
clientId: teams
existingSecret: keycloak-client-secret
clientSecretKey: client-secretExample with External Secrets Operator:
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: teams-keycloak-secret
namespace: production
spec:
refreshInterval: 1h
secretStoreRef:
name: vault-backend
kind: SecretStore
target:
name: keycloak-client-secret
data:
- secretKey: client-secret
remoteRef:
key: keycloak/teams/credentials
property: client-secretRequested Subject Template
The REQUESTED_SUBJECT_TEMPLATE environment variable controls how Teams constructs the requested_subject parameter for token exchange. This determines which Keycloak username will be impersonated.
Default: ${local}@${contextId} (produces alice@12345 from alice@domain.com with contextId 12345)
Available Placeholders:
| Placeholder | Description | Example Value |
|---|---|---|
${sub} | Full JWT subject from Switchboard token | alice@domain.com |
${userId} | User identifier from Switchboard token | alice@domain.com |
${contextId} | Numeric context ID | 12345 |
${email} | User email (if present in token) | alice@example.com |
${local} | Local part before first @ | alice |
${domain} | Domain part after first @ | domain.com |
${iss} | Issuer URL from Switchboard token | https://switchboard.example.com |
Example Configurations:
# Default - local part + context ID (backwards compatible)
REQUESTED_SUBJECT_TEMPLATE=${local}@${contextId}
# Result: alice@12345
# Full email as username (if Keycloak usernames match Switchboard subjects)
REQUESTED_SUBJECT_TEMPLATE=${sub}
# Result: alice@domain.com
# Email claim (requires email claim in Switchboard token)
REQUESTED_SUBJECT_TEMPLATE=${email}
# Result: alice@example.comImportant: The resulting requested_subject must match a username in Keycloak. Ensure your user provisioning aligns with the configured template.
Authentication Mode Detection
When TOKEN_EXCHANGE_ISSUER_URL is configured, Teams uses token exchange with impersonation. Otherwise, it falls back to the legacy Switchboard authentication API. This allows gradual migration without requiring simultaneous infrastructure changes.
Verification and Testing
1. Test Token Exchange
Test the token exchange flow manually (replace placeholders with your values):
# Get service account token
SERVICE_TOKEN=$(curl -s -X POST \
"https://your-keycloak/realms/your-realm/protocol/openid-connect/token" \
-u "teams:your-secret" \
-d "grant_type=client_credentials" \
| jq -r '.access_token')
# Exchange for user token (replace "testuser" with actual username)
curl -X POST \
"https://your-keycloak/realms/your-realm/protocol/openid-connect/token" \
-u "teams:your-secret" \
-d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
-d "subject_token=$SERVICE_TOKEN" \
-d "subject_token_type=urn:ietf:params:oauth:token-type:access_token" \
-d "requested_subject=testuser" \
-d "requested_token_type=urn:ietf:params:oauth:token-type:access_token" \
-d "scope=read_mail read_mailaccount" \
-d "audience=appsuite-mw"2. Verify Token Claims
Decode the exchanged token at jwt.io and verify the following claims:
Required claims:
- iss: Matches your Keycloak realm issuer
- azp: Should be
teams(authorized party) - scope: Contains
read_mailaccount read_mail - login: Contains the login claim in format
userLocalPart@contextId(e.g.,alice@12345) - REQUIRED by MW - exp: Token expiration is set appropriately
Optional claims:
- aud: Contains the App Suite MW client ID (only if MW validates audience)
- userId: Contains the user's identifier (for debugging/logging)
- contextId: Contains the user's context ID (for debugging/logging)
3. Test with Teams Service
Start Teams with the configured environment variables and verify logs show successful token exchange.
Troubleshooting
Error: "Parameter 'requested_subject' is not supported"
Cause: The token-exchange feature flag is not enabled.
Solution: Enable the feature flag and restart Keycloak:
KC_FEATURES=token-exchangeError: "Token exchange not allowed"
Cause: Missing impersonation permissions.
Solution:
- Verify Teams client has Service accounts roles enabled
- Verify Teams client has Client authentication enabled (confidential)
- Check that
impersonationrole is assigned to the Teams service account
Error: "Invalid client credentials"
Cause: Client secret is incorrect.
Solution:
- Verify
TOKEN_EXCHANGE_CLIENT_SECRETmatches Keycloak (Clients → teams → Credentials) - Regenerate the secret if needed and update your environment configuration
Error: "User not found" or "Cannot impersonate user"
Cause: User doesn't exist in Keycloak or has mismatched identity.
Solution:
- Verify user exists in Keycloak with username matching the
requested_subjectsent by Teams - Check Teams logs to see what
requested_subjectwas sent - Ensure users have the login attribute configured (e.g.,
appsuite-loginwith formatlocalpart@contextId) - If using dynamic user creation, verify the Keycloak extension is properly configured and enabled
Error: "Invalid token" from App Suite MW
Cause: Token missing required claims or wrong audience.
Solution:
- Verify
audienceparameter matches App Suite MW client ID (if audience validation is enabled in MW) - Check user has the login attribute configured with correct format:
- Attribute name must match your mapper configuration (e.g.,
appsuite-login) - Value must be in format
userLocalPart@contextId(e.g.,alice@12345)
- Attribute name must match your mapper configuration (e.g.,
- Verify the
loginprotocol mapper is configured correctly:- Mapper type must be User Attribute
- User Attribute field must match your user attribute name
- Token Claim Name must be
login
- Decode the JWT token and verify it contains the
loginclaim:- Use jwt.io or
echo $TOKEN | cut -d'.' -f2 | base64 -d | jq - If
loginclaim is missing, check mapper configuration and user attribute
- Use jwt.io or
Token expires too quickly
Solution: Adjust token lifespan in Keycloak (Realm Settings → Tokens → Access Token Lifespan)
Error: "REQUESTED_SUBJECT_TEMPLATE produced empty result"
Cause: The template resolved to an empty string because required claims are missing.
Solution:
- Check that required claims exist in the Switchboard token (e.g.,
sub,userId,contextId) - Use Teams debug logs to see what claims are available in the validated token
- Verify the template syntax is correct (use
${placeholder}format) - If using
${email}, ensure the Switchboard token includes an email claim
Error: "Unknown placeholder '${xxx}' in REQUESTED_SUBJECT_TEMPLATE"
Cause: The template contains an unsupported placeholder.
Solution:
- Only use supported placeholders:
${sub},${userId},${contextId},${email},${local},${domain},${iss} - Check for typos in placeholder names
- Placeholder names are case-sensitive
Security Considerations
- Minimal Scopes: Teams explicitly requests only the required scopes during token exchange (
read_mail,read_mailaccount). Configure these as Optional scopes in Keycloak to enforce principle of least privilege. - Audience Scoping: Use
audienceparameter to limit token validity to specific resource servers - Secret Management: Store
TOKEN_EXCHANGE_CLIENT_SECRETsecurely using external secret management:- Recommended: Use
tokenExchange.existingSecretwith External Secrets Operator, Sealed Secrets, or cert-manager - Avoid: Hardcoding secrets in Helm values files or environment variables
- Best Practice: Rotate secrets regularly using your secret management system
- Recommended: Use
- Audit Logging: Enable Keycloak event logging for
TOKEN_EXCHANGEevents to monitor impersonation activities

