Sub topic 7
Web server flow: acting on behalf of a user
This chapter assumes you have a connected app with a consumer key and secret, you know the token response fields, and you can call the REST API with a bearer token. Here you build the full web server flow. It is the OAuth 2.0 authorization code grant, and it is the right choice when your application acts as the person who logged in.
What the flow does
The web server flow lets a user approve your app without ever giving the app their password. The user types credentials only on a Salesforce login page. Your app receives a one-time authorization code and trades it for tokens.
The access token carries the identity and permissions of that user. Field-level security, sharing rules, and object permissions all apply as if the user were making the calls. Each user who signs in produces a separate token, so audit trails show the real person.
The flow has two legs.
- Front channel. The browser goes to Salesforce, the user logs in and approves, and Salesforce redirects the browser back to your callback URL with a
code. - Back channel. Your server posts the code to the token endpoint, together with the consumer secret, and receives tokens. The browser never sees the tokens or the secret.
Connected app settings
Before the flow works, the connected app needs these settings.
- Callback URL. The
redirect_uriyou send must match a registered callback URL exactly. Production URLs must use HTTPS. A mismatch in scheme, host, path, or a trailing slash causesredirect_uri_mismatch. - Selected OAuth scopes. Include
apifor REST access. Addrefresh_tokenif the app must keep working after the access token expires. - Secret handling. By default the token request must include
client_secret. Only relax this for clients that cannot keep a secret, and then rely on PKCE.
Step 1: send the user to authorize
Your server builds the authorization URL and redirects the browser to it.
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=S256| Parameter | Purpose |
|---|---|
| `response_type=code` | Selects the authorization code grant. |
| `client_id` | The consumer key of the connected app. |
| `redirect_uri` | Where Salesforce sends the browser afterward. Must match the registered callback URL. |
| `scope` | Space-separated scopes, URL-encoded. |
| `state` | A random value you generate and check later. |
| `code_challenge`, `code_challenge_method` | The PKCE challenge. The next chapter covers it in detail. |
Use https://test.salesforce.com for sandboxes. If users sign in through a custom domain, use your My Domain URL as the host so they land on the right login page.
Step 2: receive the callback
After the user approves, Salesforce redirects to your callback URL with code and state query parameters. If the user denies access or something fails, you get error and error_description instead. Handle that case before reading code.
Compare the returned state with the value you stored for this browser session. If they differ, stop. Someone may be trying to inject a code into the user's session (a cross-site request forgery attack).
Step 3: exchange the code
The code is short-lived and works once. Post it to the token endpoint from your server.
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 redirect_uri here must equal the one used in step 1. The response contains access_token, instance_url, and id. It also contains a refresh_token if you requested that scope. Send API calls to instance_url, not to the login host.
A complete server-side example
This Flask app runs both legs. It keeps state and the PKCE verifier in the server-side session. It reads secrets from environment variables, not from source code.
import base64
import hashlib
import os
import secrets
import requests
from flask import Flask, abort, redirect, request, session
app = Flask(__name__)
app.secret_key = os.environ["FLASK_SECRET_KEY"]
LOGIN_URL = "https://login.salesforce.com"
CLIENT_ID = os.environ["SF_CONSUMER_KEY"]
CLIENT_SECRET = os.environ["SF_CONSUMER_SECRET"]
REDIRECT_URI = "https://app.example.com/oauth/callback"
def b64url(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
@app.route("/login")
def login():
state = secrets.token_urlsafe(32)
verifier = b64url(os.urandom(64))
challenge = b64url(hashlib.sha256(verifier.encode()).digest())
session["state"] = state
session["verifier"] = verifier
url = requests.Request(
"GET",
f"{LOGIN_URL}/services/oauth2/authorize",
params={
"response_type": "code",
"client_id": CLIENT_ID,
"redirect_uri": REDIRECT_URI,
"scope": "api refresh_token",
"state": state,
"code_challenge": challenge,
"code_challenge_method": "S256",
},
).prepare().url
return redirect(url)
@app.route("/oauth/callback")
def callback():
if "error" in request.args:
abort(400, request.args.get("error_description", "Authorization failed"))
expected = session.pop("state", "")
returned = request.args.get("state", "")
if not expected or not secrets.compare_digest(expected, returned):
abort(400, "State mismatch")
resp = requests.post(
f"{LOGIN_URL}/services/oauth2/token",
data={
"grant_type": "authorization_code",
"code": request.args["code"],
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_uri": REDIRECT_URI,
"code_verifier": session.pop("verifier"),
},
timeout=10,
)
if resp.status_code != 200:
abort(502, resp.text)
token = resp.json()
# Store token["access_token"] and token.get("refresh_token") server-side,
# keyed to this user. Never put them in a URL or in browser-readable storage.
return f"Signed in. Your org is {token['instance_url']}"Run it behind HTTPS at the registered callback URL. Visiting /login starts the flow.
Common edge cases
- Code reuse. Presenting the same code twice, or after it expires, returns
invalid_grant. Do not retry a failed exchange with the same code. Restart the flow. - Verifier mismatch. If
code_verifierdoes not hash to the challenge sent in step 1, the exchange fails withinvalid_grant. This usually happens when the verifier was not stored per session. - No refresh token. If the
refresh_tokenscope was not requested and approved, the response omits it. Users then have to sign in again when the access token expires. - Wrong login host. An org that uses My Domain login or a sandbox needs the matching host. Sending a sandbox user to
login.salesforce.comfails at login. - Approval policies. If the connected app limits access to admin-approved users, an unapproved user is blocked at login. Check the app's permitted-users policy.
Exercise
A user signs in, and your callback exchange returns invalid_grant. You confirmed the callback URL matches. Name two likely causes in the web server flow and how you would check each.
Show answer
The authorization code may have been used already or may have expired. Check the logs for a repeated request to the callback, such as a browser refresh, and restart the flow with a fresh login. The code_verifier may not match the code_challenge from the authorize request. Check that the verifier is stored per session and that the challenge is the base64url-encoded SHA-256 hash of that exact verifier.