Sub topic 11
Setting up OAuth 2.0 with an authentication provider
This chapter assumes you can already create a Named Credential, an External Credential and a principal, and that you know what a permission set does. It also assumes you know the OAuth 2.0 vocabulary: client ID, client secret, scope, access token, refresh token and redirect URI. Here you will connect an External Credential to an OAuth 2.0 service by using an authentication provider.
What changes compared with an API key
With an API key, the secret is a static value that you store as an authentication parameter. With OAuth 2.0, the secret is a short-lived access token. Salesforce obtains the token, stores it, refreshes it, and adds an Authorization: Bearer header to each callout. Your Apex code does not change. It still sets the endpoint to callout:Name/path and sends the request.
The extra work is all in Setup:
- Register Salesforce as a client in the external system.
- Create an authentication provider in Salesforce.
- Point the External Credential at that provider.
- Authenticate a principal so that Salesforce holds a token.
Choosing an OAuth flow
The External Credential's OAuth 2.0 protocol offers several flow types. Only one of them uses an authentication provider.
| Flow type | Uses an authentication provider | Typical use |
|---|---|---|
| Browser Flow | Yes | A person signs in at the external system and approves access. |
| JWT Bearer Flow | No | Server-to-server access with a signed assertion and a certificate. |
| Client Credentials | No | Server-to-server access with a client ID and secret or certificate. |
Use Browser Flow when the external system must know which person is calling, or when it only supports the authorization code grant. Use a server-to-server flow when no person is involved. For those flows you enter the identity provider URL and client details directly on the External Credential, so you can skip steps 2 and 3 below.
Step 1: Register Salesforce in the external system
In the external system's developer console, create an OAuth client (some systems call it an app or an application). You need to set three things:
- A redirect URI. You do not have this yet, because Salesforce generates it in step 2. Leave it blank or use a placeholder and come back.
- The scopes the client may request.
- The grant type, which is authorization code for Browser Flow.
Record the client ID and client secret. Also note the authorize endpoint and the token endpoint, which are usually listed in the provider's documentation.
Step 2: Create the authentication provider
In Setup, open Auth. Providers and choose a provider type. Use a specific type if one exists for your service, such as Google or Salesforce. Otherwise use OpenID Connect, which works for any service that follows the standard.
An outline of the settings for an OpenID Connect provider:
Auth. Provider: Partner_OIDC
Provider Type: OpenID Connect
Name: Partner OIDC
URL Suffix: Partner_OIDC
Consumer Key: <client ID from the external system>
Consumer Secret: <client secret from the external system>
Authorize Endpoint URL: https://login.partner.example/oauth2/authorize
Token Endpoint URL: https://login.partner.example/oauth2/token
Default Scopes: openid offline_access orders.readAfter you save, Salesforce shows a Callback URL in the form https://<your domain>/services/authcallback/Partner_OIDC. Copy it and register it as a redirect URI in the external system. If the two values differ by even one character, the sign-in fails later with a redirect mismatch error.
Step 3: Connect the External Credential
Create or edit the External Credential and set these fields:
External Credential: Partner_EC
Authentication Protocol: OAuth 2.0
Authentication Flow Type: Browser Flow
Scope: openid offline_access orders.read
Authentication Provider: Partner_OIDC
Principal: Partner_Principal (Named Principal)The scope you enter here is what Salesforce requests during sign-in. Make sure it includes whatever the provider requires to issue a refresh token. Many providers need offline_access or a similar scope. Without a refresh token, callouts work until the access token expires and then fail until someone signs in again.
Then create the Named Credential as in earlier chapters. Set its URL to the API base, point it at Partner_EC, and do not add an authorization header yourself. Salesforce adds the bearer token.
Step 4: Authenticate the principal
Saving a principal does not give Salesforce a token. The principal's authentication status starts as Not Configured. What you do next depends on the principal type.
- Named principal. An administrator opens the principal in the External Credential and chooses Authenticate. Salesforce redirects to the external system, the administrator signs in and approves, and the status changes to Configured. Every user with access to the principal then makes callouts as that one identity.
- Per user principal. Each user authenticates for themselves. The next chapter covers that flow.
Behind the scenes, the sequence looks like this:
Step 5: Grant access and call the service
The permission set rule from earlier chapters still applies. A user can only call through the credential if one of their permission sets includes External Credential Principal Access for Partner_EC - Partner_Principal. A configured principal does not remove this requirement.
The Apex code holds no OAuth details:
public with sharing class PartnerOrderService {
public static String getOrder(String orderId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_API/orders/' + EncodingUtil.urlEncode(orderId, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Partner API returned status ' + res.getStatusCode());
}
return res.getBody();
}
}Run it from Anonymous Apex as a user who has the permission set:
System.debug(PartnerOrderService.getOrder('A-1001'));Token lifecycle and what you cannot see
Salesforce stores the tokens and does not expose them to Apex. You cannot read the access token, and you should not try to copy it into a header. When the access token expires, Salesforce uses the refresh token to get a new one. This happens inside the callout and your code is unaware of it.
Tokens can stop working for reasons outside Salesforce:
- The external user revokes the app's access.
- The refresh token expires or is rotated by the provider.
- An administrator changes the client secret in the external system.
- The scopes on the client change.
When this happens, callouts fail until someone re-authenticates the principal. For a named principal, that is an administrator action. Plan for it by monitoring callout failures, not by assuming the setup is permanent.
Common errors in OAuth setup
| Symptom | Likely cause | Fix |
|---|---|---|
| Redirect mismatch error during sign-in | The callback URL registered externally differs from the one Salesforce shows | Copy the callback URL again from the authentication provider and register it exactly. |
| Principal stays Not Configured | Sign-in was never completed, or the provider rejected it | Run **Authenticate** again and read the error shown on return. |
| Callouts work, then fail after about an hour | No refresh token was issued | Add the scope your provider needs for refresh tokens, then authenticate again. |
| 401 from the external API | Token revoked, expired without refresh, or wrong scopes | Re-authenticate and check the scopes on both sides. |
| 403 from the external API | The token is valid but lacks permission for that resource | Add the missing scope to the client and to the External Credential, then re-authenticate. |
| Error saying the user cannot access the credential | The permission set lacks principal access | Add External Credential Principal Access to a permission set the user holds. |
Summary of the roles
- The external system issues tokens and defines scopes.
- The authentication provider holds the client ID, client secret and endpoints.
- The External Credential selects the flow, requests scopes and holds principals.
- The Named Credential supplies the base URL.
- The permission set decides who may use the principal.
- Apex only writes
callout:Name/path.
Exercise
You configured a Browser Flow External Credential with a named principal. An administrator authenticated it successfully and the status shows Configured. A standard user runs the Apex callout and it fails, while the administrator's callout succeeds. Callouts also started failing for everyone about an hour after setup, even for the administrator. Name the likely cause of each problem and the fix.
Show answer
The standard user's failure is most likely missing access: none of their permission sets includes External Credential Principal Access for the principal, so add it to a permission set they hold. The failure after about an hour for everyone suggests that no refresh token was issued, so the access token expired and could not be renewed. Add the scope the provider needs for refresh tokens, such as offline_access, to the authentication provider and the External Credential, then authenticate the principal again.
Exercise
A teammate asks why the Apex class does not set an Authorization header with the access token. What do you tell them, and why can't the class do it anyway?
Show answer
Salesforce adds the bearer token itself when the callout uses a Named Credential whose External Credential has an authenticated principal. Apex cannot read the stored token, so it could not build the header even if it tried. Setting a header by hand would also bypass the refresh logic and the permission set check.