Skip to content
Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
DictionaryTToken Exchange Handlers
DevelopmentIntermediate

Token Exchange Handlers

Token Exchange Handlers is the Salesforce Setup page for registering and managing Apex classes that implement custom OAuth 2.0 token exchange flows. The classes plug into Salesforce's identity laye…

§ 01

Definition

Token Exchange Handlers is the Salesforce Setup page for registering and managing Apex classes that implement custom OAuth 2.0 token exchange flows. The classes plug into Salesforce's identity layer at the moment a token from one identity provider needs to be converted into a Salesforce session or a token for another system, executing custom logic for validation, claims mapping, and session establishment.

The feature implements the OAuth 2.0 Token Exchange specification (RFC 8693), which standardizes how a client can exchange one token for another in scenarios like cross-organization SSO, agent-to-agent delegation, machine-to-machine federation, and identity propagation across cloud boundaries. The handler classes implement the Auth.TokenExchangeHandler interface and define what happens when Salesforce receives a token exchange request: validate the incoming token, map claims to a Salesforce user, mint the response token, and return it to the caller.

§ 02

How Token Exchange Handlers fit into identity architecture

The OAuth Token Exchange specification

RFC 8693 defines a standard token exchange grant where a client presents one token (the subject token) to an authorization server and requests another token in return. The exchange can be impersonation (act as the same user) or delegation (act on behalf of a user with reduced scope). Salesforce's Token Exchange Handlers implement the server-side of this exchange: when an incoming request arrives with the urn:ietf:params:oauth:grant-type:token-exchange grant type, Salesforce routes it to the configured handler class, which decides what to do. The grant type, token type identifiers, and response format all follow the RFC, making the implementation interoperable with any compliant client.

The Auth.TokenExchangeHandler interface

Custom handlers extend the abstract Auth.TokenExchangeHandler class and implement two methods. validateToken validates the incoming subject token against the trusted issuer (verifying signature, expiration, audience, and any custom claims). validateAndExchangeToken performs the validation and then maps the validated identity to a Salesforce user or determines how to mint the response token. The Apex class lives in the org's metadata and is referenced by name on the Token Exchange Handler Setup page. Salesforce calls the methods automatically when token exchange requests arrive at the configured endpoint, passing the request parameters and expecting a response object back.

Use cases that require custom handlers

Three scenarios commonly require Token Exchange Handlers. Cross-organization SSO between two Salesforce orgs (a parent company and a subsidiary) where the user signs into one and needs to access the other without re-authenticating. Machine-to-machine federation where a background process running in a third-party system needs to call Salesforce APIs with a federated identity rather than a service account. Agentforce delegation where an LLM agent acts on behalf of a user, requiring a token that represents the user but scoped to the specific tools the agent can use. Each scenario has its own claims mapping logic, audit requirements, and approval workflows that the handler class encodes.

Claims mapping and user provisioning

The handler validates the subject token and then needs to determine which Salesforce user the resulting session represents. The standard pattern reads claims from the subject token (typically a sub claim with the user identifier, plus custom claims for department, role, or scope) and queries Salesforce for the matching user record. If no matching user exists, the handler can call standard provisioning APIs to create one on demand, then return the token for the new user. The exact rules depend on the org's identity governance: some orgs allow on-demand provisioning, others require a pre-provisioned user before any token can be issued.

Audit and observability

Every token exchange generates a Login History record and a Setup Audit Trail entry. The Login History entry shows when the token was issued, which handler processed the request, and the identity that was federated in. The Setup Audit Trail entry records the handler invocation. For organizations with regulatory audit requirements, the handler class can also write its own Custom Object records capturing claim values, source identity provider, target user, and any custom audit fields. The combination of platform-level audit and handler-level audit gives a complete view of every federated identity that flowed through the system, which is what regulators usually require for SOX and HIPAA compliance.

Security considerations

Token Exchange Handlers are sensitive identity-layer code. A bug or vulnerability can let an attacker mint a Salesforce session for any user. Several controls are mandatory: signed-token validation using public keys from a trusted JWKS endpoint, audience and issuer verification on every request, time-bound token validity, and explicit handler logic that fails closed on any unexpected claim shape. Every change to a handler class should go through code review by someone with identity expertise. The class should run with the minimum permissions needed and should never expose internal user data in error responses. Treat handler code like cryptographic code: rare to write, important to write well, and always reviewed.

Alternative: built-in token exchange flows

For many use cases, Salesforce's built-in token exchange flows (configured through Auth Providers, Connected Apps, and SAML Identity Provider settings) cover the requirement without writing a custom handler. Cross-org SSO between Salesforce orgs can often be done with the standard Salesforce-as-IdP flow plus a Connected App. Machine-to-machine federation can use JWT bearer flow with a trusted JWKS. Custom handlers are the right answer when none of the built-in flows match the scenario: complex claim mapping, dynamic scope decisions, on-demand provisioning, or integration with a non-standard identity provider. Always check whether a built-in flow works before writing a handler.

Operational lifecycle of a deployed handler

After a Token Exchange Handler reaches production, the operational discipline determines whether it stays secure. Three operational practices apply. Key rotation: trusted issuers rotate their signing keys on a schedule, and the handler must fetch the JWKS at request time or cache it with a short TTL. Hardcoding a key freezes that key in place and breaks the handler the moment rotation happens. Volume monitoring: token exchange requests are a security-relevant event, and a sudden spike is a signal that either a legitimate integration scaled up or an attacker is probing. Build a dashboard against the Login History records filtered to token exchange events, with thresholds that page the security team on anomalies. Periodic re-review: schedule a semi-annual review of every handler against the current threat model, the current OAuth specifications, and the current set of trusted issuers. Trusted issuers go out of business, change ownership, or have their own security incidents, and a handler that trusted them yesterday should not necessarily trust them tomorrow without re-verification.

§ 03

Implement and register a Token Exchange Handler

Implementing a Token Exchange Handler is identity-layer work that requires Apex skills, OAuth knowledge, and careful security review. The walkthrough below covers the standard implementation flow from initial design through production registration.

  1. Design the exchange scenario and security model

    Document what the exchange is supposed to accomplish, the trusted issuer of the subject token, the claims to validate, the mapping rule from claims to Salesforce user, and the audit requirements. Review the design with the org's security team. Identify any compliance constraints (SOX, HIPAA, regional privacy laws) that affect the handler's behavior. Approve the design before writing code; identity-layer code that gets implemented before design review usually has security gaps that surface during audit.

  2. Implement the Apex handler class

    Create an Apex class extending Auth.TokenExchangeHandler. Implement validateToken to verify the subject token's signature against a trusted JWKS, check issuer and audience, and validate expiration. Implement validateAndExchangeToken to perform the validation and then look up or provision the matching Salesforce user. Return the appropriate response token. Cover the implementation with unit tests targeting at least 90% coverage and explicitly testing every failure mode (invalid signature, expired token, missing claim, no matching user).

  3. Register the handler in Setup

    From Setup, navigate to Token Exchange Handlers and click New. Provide a name, a description, the Apex class reference, and the endpoint configuration the handler should respond to. Configure the trusted issuer details (JWKS URL, allowed audiences). Save and enable the handler. Test by sending a sample token exchange request from a test client and verifying the returned token works for subsequent API calls. Iterate until the test cases from the design document all pass.

  4. Promote to production with security signoff

    Schedule production deployment during a low-traffic window. Deploy the Apex class through the standard pipeline (Change Sets, DevOps Center, or SFDX). Register the handler in production with the production trusted issuer details. Run an end-to-end test from a production client and confirm the exchange works as designed. Update the org's identity architecture documentation with the new handler, its purpose, and its security model. Schedule a six-month review of the handler against new threat models and new OAuth specifications.

Gotchas
  • Token signature validation must use the trusted issuer's public keys from a JWKS endpoint. Hardcoding a single public key breaks when the issuer rotates keys.
  • Audience verification is mandatory. A handler that does not check the audience claim accepts tokens intended for other systems, which is a serious vulnerability.
  • Error responses must not leak internal information. Return generic 401 Unauthorized for any validation failure, log details internally for debugging.
  • On-demand user provisioning needs governance. A handler that creates a new user for every unknown subject token quickly fills the org with stale accounts.
  • Handler classes run synchronously in the token exchange request path. Slow validation logic times out the exchange and breaks client integrations.
§

Trust & references

Sources

Cross-checked against the following references.

Official documentation

Straight from the source - Salesforce's reference material on Token Exchange Handlers.

Keep learning

Hands-on resources to go deeper on Token Exchange Handlers.

Was this entry helpful?
Help us write better definitions. Quick reactions or detailed edit suggestions.

About the Author

Dipojjal Chakrabarti is a B2C Solution Architect with 29 Salesforce certifications and over 13 years in the Salesforce ecosystem. He runs salesforcedictionary.com to help admins, developers, architects, and cert/interview candidates sharpen their fundamentals. More about Dipojjal.

§

Test your knowledge

Q1. What skill set is typically needed to work with Token Exchange Handlers?

Q2. What is required before deploying Token Exchange Handlers-related code to production?

Q3. Where would a developer typically work with Token Exchange Handlers?

§

Discussion

Loading…

Loading discussion…