How does the OAuth 2.0 Web Server Flow secure token exchanges for server-side external applications?
Answer
Basics: It is designed for apps with a secure server side (a web app, an integration portal) that can keep a secret. The user's credentials go only to Salesforce. The app obtains tokens to call APIs on behalf of that user.
How it works:
- The app redirects the browser to
/services/oauth2/authorizewithresponse_type=code,client_id,redirect_uri,scope,stateand optionallycode_challenge(PKCE). - The user logs in and approves.
- Salesforce redirects back with
?code=...&state=.... - The server verifies
state, then POSTs to/services/oauth2/tokenwithgrant_type=authorization_code, the code,client_id,client_secret,redirect_uriandcode_verifier. - Response includes
access_token,refresh_token(ifrefresh_tokenscope),instance_url,id,issued_at, andid_tokenwithopenid. - The server stores tokens securely and calls APIs; when the access token expires, it uses
grant_type=refresh_token.
Advanced / deep dive: Security layers: the code is single-use and expires quickly; the secret authenticates the client; state prevents CSRF; PKCE protects against code interception and is recommended even for confidential clients (and required to make public clients safe). Access token lifetime follows the session timeout of the Connected App or org; refresh tokens persist per the refresh token policy (for example until revoked or valid for N days). Revoke through . For machine-to-machine flows with no user, prefer JWT Bearer or Client Credentials. For multi-tenant apps, handle sandbox () versus production hosts, and prefer My Domain URLs. Keep tokens encrypted at rest and scope them narrowly.