Skip to content

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:

  1. User authenticates via Switchboard, Teams receives a user JWT
  2. Teams validates the Switchboard token locally (signature and claims verification)
  3. Teams obtains a service account token from Keycloak (client credentials grant)
  4. Teams exchanges the service account token for a user token using impersonation
  5. 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-exchange

Note: 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

  1. Navigate to Clients in your Keycloak realm

  2. 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)
  3. In the Credentials tab:

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

2. Configure Client Scopes

The Teams service explicitly requests the scopes it needs during token exchange. Configure these scopes in Keycloak:

  1. Navigate to Client Scopes

  2. Create scopes if they don't exist:

    • read_mailaccount - Permission to read mail account information
    • read_mail - Permission to read mail messages
  3. Assign scopes to the Teams client:

    • Navigate to Clients → teams → Client Scopes tab
    • Add read_mailaccount and read_mail as 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:

  1. Navigate to Clients → teams → Service account roles tab
  2. Click Assign role
  3. Filter by clients: Select realm-management
  4. 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:

  1. Navigate to Clients and find your App Suite MW client (e.g., appsuite-mw)
  2. Note the Client ID - this will be used as the audience parameter in Teams configuration
  3. 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: login

Create a protocol mapper to include the required login claim in exchanged tokens:

  1. Navigate to Client Scopes → Create new scope:

    • Name: appsuite-user-identity
    • Protocol: openid-connect
  2. 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-login if using the dynamic user provider extension (Approach 2).

  3. 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
    • contextId mapper (optional):

      • Mapper Type: User Attribute
      • Name: contextId
      • User Attribute: contextId
      • Token Claim Name: contextId
      • Add to access token: ON
  4. 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:

  1. Username Matching: The requested_subject sent by Teams must match a username in Keycloak

    • Example: If Teams sends requested_subject: "alice@12345", a Keycloak user with username alice@12345 must exist
  2. 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
  3. 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 token
  • scope: Explicitly requested scopes (space-delimited) - Teams requests read_mail read_mailaccount
  • audience: 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 Keycloak
  • AUDIENCE - (Optional) App Suite MW client ID. Only required if your MW deployment validates the aud claim. Omit if unsure - tokens work without it if MW doesn't check audience.
  • REQUESTED_SUBJECT_TEMPLATE - (Optional) Template for constructing the requested_subject parameter. 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 secret

Recommended: 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-secret

Example 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-secret

Requested 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:

PlaceholderDescriptionExample Value
${sub}Full JWT subject from Switchboard tokenalice@domain.com
${userId}User identifier from Switchboard tokenalice@domain.com
${contextId}Numeric context ID12345
${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 tokenhttps://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.com

Important: 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-exchange

Error: "Token exchange not allowed"

Cause: Missing impersonation permissions.

Solution:

  1. Verify Teams client has Service accounts roles enabled
  2. Verify Teams client has Client authentication enabled (confidential)
  3. Check that impersonation role is assigned to the Teams service account

Error: "Invalid client credentials"

Cause: Client secret is incorrect.

Solution:

  1. Verify TOKEN_EXCHANGE_CLIENT_SECRET matches Keycloak (Clients → teams → Credentials)
  2. 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:

  1. Verify user exists in Keycloak with username matching the requested_subject sent by Teams
  2. Check Teams logs to see what requested_subject was sent
  3. Ensure users have the login attribute configured (e.g., appsuite-login with format localpart@contextId)
  4. 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:

  1. Verify audience parameter matches App Suite MW client ID (if audience validation is enabled in MW)
  2. 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)
  3. Verify the login protocol 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
  4. Decode the JWT token and verify it contains the login claim:
    • Use jwt.io or echo $TOKEN | cut -d'.' -f2 | base64 -d | jq
    • If login claim is missing, check mapper configuration and user attribute

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:

  1. Check that required claims exist in the Switchboard token (e.g., sub, userId, contextId)
  2. Use Teams debug logs to see what claims are available in the validated token
  3. Verify the template syntax is correct (use ${placeholder} format)
  4. 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:

  1. Only use supported placeholders: ${sub}, ${userId}, ${contextId}, ${email}, ${local}, ${domain}, ${iss}
  2. Check for typos in placeholder names
  3. 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 audience parameter to limit token validity to specific resource servers
  • Secret Management: Store TOKEN_EXCHANGE_CLIENT_SECRET securely using external secret management:
    • Recommended: Use tokenExchange.existingSecret with 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
  • Audit Logging: Enable Keycloak event logging for TOKEN_EXCHANGE events to monitor impersonation activities

References