Sub topic 2
Web Server and JWT Bearer Flows
Assume you know HTTP redirects, JSON, curl, Salesforce connected apps, and basic public/private key pairs. The web server flow lets an application act for a user after that user approves access.
Web server flow
Send the browser to Salesforce’s authorization endpoint. Include the connected app’s consumer key, an exact callback URL, requested scopes, a random state value, and a PKCE challenge.
https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=<CONSUMER_KEY>&redirect_uri=https%3A%2F%2Fapp.example.com%2Foauth%2Fcallback&scope=api%20refresh_token&state=<RANDOM_STATE>&code_challenge=<S256_CHALLENGE>&code_challenge_method=S256After approval, Salesforce redirects to the callback with a short-lived authorization code. Your server exchanges it for tokens:
curl -X POST https://login.salesforce.com/services/oauth2/token \
-d grant_type=authorization_code \
-d code=<AUTHORIZATION_CODE> \
-d client_id=<CONSUMER_KEY> \
-d client_secret=<CONSUMER_SECRET> \
-d redirect_uri=https://app.example.com/oauth/callback \
-d code_verifier=<CODE_VERIFIER>The server then sends the access token as Authorization: Bearer <token> to the returned instance_url.
State and PKCE
state is a random value stored in the user’s session. Compare it with the returned value to prevent a forged callback. PKCE binds the authorization request to the token request. Keep the verifier secret and send its derived SHA-256 challenge to Salesforce.
Refreshing an access token
Request the refresh_token scope when the application needs continued access. When the access token expires, use the refresh token:
curl -X POST https://login.salesforce.com/services/oauth2/token \
-d grant_type=refresh_token \
-d refresh_token=<REFRESH_TOKEN> \
-d client_id=<CONSUMER_KEY> \
-d client_secret=<CONSUMER_SECRET>JWT bearer flow
For unattended server-to-server access as a named user, configure the connected app with a certificate and pre-authorize that user through its policies, profile, or permission set.
Create a private key and certificate. Keep server.key only on the integration server; upload server.crt to the connected app.
openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 \
-keyout server.key -out server.crt -subj "/CN=sf-jwt-integration"The server signs a short-lived RS256 JWT. Its iss is the consumer key, sub is the Salesforce username, and aud is the login URL. Post the signed assertion with grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer. Salesforce returns an access token without an interactive login.
Exercise
Why must a server verify state before exchanging an authorization code?
Show answer
It confirms that the callback belongs to the login attempt started by that user session.