Sub topic 1
OAuth 2.0 in Salesforce: roles, grants, and tokens
Prerequisites
Assume you know HTTP methods, headers, redirects, form-encoded requests, JSON, and basic curl. You also need a Salesforce org and administrator access.
OAuth 2.0 is an authorization framework. It lets an application obtain a token instead of handling a Salesforce user's password.
The main roles are:
- Resource owner: The Salesforce user who grants access.
- Client: Your application or integration.
- Authorization server: Salesforce's OAuth service, which grants tokens.
- Resource server: The Salesforce API, which accepts tokens.
A grant is an OAuth method for obtaining a token. An access token is a short-lived credential used on API requests. A refresh token can obtain a new access token without another user login.
Endpoints and My Domain
Use your Salesforce login host for the authorization-code and JWT flows:
- Production:
https://login.salesforce.com - Sandbox:
https://test.salesforce.com
For client credentials, use the org's My Domain host, such as https://example.my.salesforce.com. My Domain gives the org a stable, unique hostname and is required for several org-specific OAuth operations.
The authorization endpoint starts a user login. The token endpoint exchanges a grant for tokens:
https://login.salesforce.com/services/oauth2/authorize
https://login.salesforce.com/services/oauth2/tokenSetting up a connected app
A connected app is a Salesforce configuration that represents an external application. Configure its callback URL, OAuth scopes, and policy settings. The callback URL must exactly match the URL sent in an authorization request, including its scheme, host, path, and sometimes trailing slash.
The app receives a consumer key and, for confidential applications, a consumer secret. Store both as secrets. Never place them in browser code or source control.
Choosing OAuth scopes
Scopes limit what an access token can do. Request the smallest set that supports the integration. Common examples include:
| Scope | Purpose |
|---|---|
| `api` | Access Salesforce APIs |
| `refresh_token` | Request a new access token later |
| `openid` | Request OpenID Connect identity information |
Connected-app policies can also restrict users, session duration, and whether users approve the app.
Reading the token response
A successful token response commonly contains access_token, instance_url, token_type, and sometimes refresh_token. Use the returned instance_url; do not assume that the login host is the API host.
Calling the REST API
Send the access token as a bearer token:
curl "$INSTANCE_URL/services/data/v60.0/limits" \
-H "Authorization: Bearer $ACCESS_TOKEN"Exercise
Why should an integration use the instance_url from the token response?
Show answer
Salesforce may place the org on a different API host. The instance_url identifies the correct resource server for that token.