Sub topic 12
Letting each user authenticate to the external system
This chapter assumes you have read the earlier chapters on principals, permission sets and OAuth 2.0 setup. You should know that an External Credential holds the authentication definition, that a Named Credential points at it, and that a permission set decides who may use a principal.
When one shared identity is not enough
A named principal gives every permitted user the same identity in the external system. That fits service integrations, such as a nightly sync that writes to a shared data store. It fits badly when the external system must know who is acting. Examples are a document service that enforces its own per-user permissions, a calendar where each person has a private account, and an audit trail that must name the real person.
A per user principal solves this. Each Salesforce user authenticates to the external system once, and Salesforce stores that user's tokens separately. When the user's Apex code makes a callout, Salesforce attaches that user's token, not a shared one.
What changes and what does not
The Apex code does not change. The same callout: endpoint works for both principal types. The difference is entirely in configuration and in who has to do what.
| Aspect | Named principal | Per user principal |
|---|---|---|
| Identity in the external system | One shared identity | One identity per Salesforce user |
| Who authenticates | An admin, once, in Setup | Each user, from their own settings |
| Permission set grants | Access to the principal | Access to the principal, plus the user must still authenticate |
| Token storage | One set per principal | One set per user per principal |
| Works in automated contexts | Yes | Only if a real, authenticated user is running the code |
Configuring a per user principal
You build this on an External Credential that uses OAuth 2.0, which you set up in the previous chapter. For a user-delegated flow, such as the authorization code flow, the steps are:
- Open the External Credential and add a principal. Set its identity type to Per User Principal and give it a name.
- Confirm that the Named Credential references this External Credential.
- Create or edit a permission set and add the principal under External Credential Principal Access. Assign it to the users who need it.
- Ask each of those users to authenticate (next section).
The outline below shows the shape of the configuration.
External Credential: Docs_EC
Authentication Protocol: OAuth 2.0 (Browser Flow)
Authentication Provider: Docs_AuthProvider
Principal: Docs_User (Per User Principal)
Named Credential: Docs_API
URL: https://docs.example.com/api
External Credential: Docs_EC
Permission Set: Docs_Callout_Access
External Credential Principal Access: Docs_EC - Docs_UserA per user principal has no stored secret in Setup, unlike the API key in the named principal example. The tokens only come into existence when a user completes the sign-in.
How a user authenticates
Permission set access lets a user attempt to use the principal. It does not give them a token. Each user must complete the sign-in themselves:
- The user opens their own personal settings and finds Authentication Settings for External Systems. This is also reachable from the user's detail page.
- The user adds a new entry and chooses the External Credential and the principal.
- Salesforce redirects the user to the external system's login page.
- The user signs in and approves the requested scopes.
- The external system redirects back to Salesforce, which stores the resulting tokens for that user.
An admin cannot complete this step for someone else. The sign-in happens in the user's own browser session with their own account at the external system. An admin can remove a user's stored credentials, which forces that user to authenticate again.
The Apex side
The code reads like any other callout. It also needs to handle the case where the running user has not authenticated yet.
public with sharing class DocsService {
public class DocsAuthException extends Exception {}
public static String getDocument(String docId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Docs_API/documents/' + EncodingUtil.urlEncode(docId, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res;
try {
res = new Http().send(req);
} catch (CalloutException e) {
// Typical when the user has no stored credentials for this principal
throw new DocsAuthException(
'Could not call the documents service. Check that you have authenticated ' +
'under Authentication Settings for External Systems. Details: ' + e.getMessage()
);
}
if (res.getStatusCode() == 401 || res.getStatusCode() == 403) {
throw new DocsAuthException(
'The documents service rejected your credentials. Re-authenticate and try again.'
);
}
if (res.getStatusCode() != 200) {
throw new CalloutException('Documents service returned status ' + res.getStatusCode());
}
return res.getBody();
}
}Wrapping the failure in a clear message matters more here than with a named principal. With a named principal, a credential failure is an admin problem. With a per user principal, it is often just a user who has not signed in yet, and the message should tell them what to do.
You test this class the same way as before, with Test.setMock and an HttpCalloutMock. The mock replaces the whole callout, so tests never exercise the per user token. Treat the sign-in flow as something you verify manually in a sandbox.
Which user's token is used
The callout uses the token of the user whose context runs the Apex. That is simple for a button click or a Lightning component, and less obvious elsewhere:
- Queueable and future methods run as the user who enqueued them.
- Scheduled Apex runs as the user who scheduled the job. If that user leaves or loses access, the job starts failing.
- Triggers on platform events and some other automated processes run as the Automated Process user, which cannot sign in to an external system through a browser. A per user principal does not work there.
- Batch Apex runs as the user who started the batch.
For anything that must run unattended, use a named principal, or have the unattended job call a separate Named Credential that uses one. Do not rely on one person's personal token for a shared background process.
Token lifecycle
Salesforce handles refresh for you. When an access token expires, it uses the stored refresh token to get a new one, and your Apex does not see this. Authentication fails and the user must sign in again in these cases:
- The user revokes the app's access in the external system.
- The refresh token expires or is invalidated by the external system's policy.
- An admin deletes the user's stored credentials.
- The scopes on the authentication provider changed and the old consent no longer covers them.
If your external system issues short-lived refresh tokens, expect users to re-authenticate regularly. Request the offline_access scope, or whatever your provider uses for refresh tokens, when you configure the authentication provider. Without a refresh token, the user has to sign in again each time the access token expires.
Common mistakes
- Granting the permission set but forgetting that users must sign in. Everything looks correct in Setup, and every callout still fails.
- Testing as an admin only. Your admin account may be authenticated while ordinary users are not. Test as a representative user.
- Using a per user principal for scheduled or event-driven code. The job runs under an identity that has no token.
- Assuming the external system maps users correctly. Salesforce stores a token per user, but the external system decides what that token may do. Authorization still lives there.
Exercise
A scheduled Apex job calls an external API through a Named Credential that uses a per user principal. It works when you schedule it, but it starts failing a month later even though nobody changed the code or the credential setup. Name two likely causes and one design change that avoids the problem.
Show answer
Likely causes: the user who scheduled the job lost the permission set that grants the principal, left the company or was deactivated, or had their stored token revoked or expired, so the job no longer has a valid per user token. Design change: use a named principal, on a service identity in the external system, for the unattended job, and keep the per user principal for interactive, user-driven callouts.