Sub topic 4
Authenticating integrations with Named Credentials
Every integration pattern in this tutorial needs a way to prove identity. A request-reply callout must authenticate to the external API. A Bulk API 2.0 job must authenticate to Salesforce. This chapter covers both directions, then focuses on Named Credentials, the Salesforce feature that keeps endpoints and secrets out of your code.
This chapter assumes you can read basic Apex, know how HTTP headers and status codes work, and have seen an OAuth access token before. You don't need to have configured a connected app.
Two directions, two mechanisms
Authentication depends on who is calling whom.
| Direction | Caller | Receiver | Typical mechanism |
|---|---|---|---|
| Inbound | External system | Salesforce (REST API, Bulk API 2.0) | OAuth 2.0 through a connected app, with an integration user |
| Outbound | Salesforce (Apex, Flow) | External system | Named Credential, backed by an External Credential |
Inbound calls use a connected app. It is the configuration record that tells Salesforce which OAuth flows, scopes, and callback URLs an external client may use. Salesforce is also introducing External Client Apps as the successor. The concepts below apply to both.
Outbound calls use a Named Credential. It is a setup record that stores the endpoint URL and a reference to how Salesforce authenticates to it.
Inbound: how external systems get into Salesforce
An external system that calls the REST API or Bulk API 2.0 sends an access token in the Authorization header:
PATCH /services/data/v60.0/sobjects/Account/External_Id__c/ERP-10042
Content-Type: application/json
Authorization: Bearer <access_token>
{
"Name": "Acme Corporation",
"Industry": "Manufacturing"
}The token comes from an OAuth 2.0 flow. Choose the flow by who or what is calling:
- JWT bearer flow. The server signs a JWT with a private key. Salesforce checks it against a certificate uploaded to the connected app. No user is present and no secret is sent over the wire. This is a common choice for server-to-server batch jobs.
- Client credentials flow. The server exchanges a client ID and secret for a token. It runs as a "run-as" user you designate on the app. It is simpler than JWT but depends on protecting the secret.
- Web server (authorization code) flow. A human approves access in a browser. Use it when the integration acts on behalf of a person.
For unattended integrations, create a dedicated integration user. Give it a permission set containing only the objects and fields the integration touches. Do not run integrations as a named employee. When that person leaves or changes roles, the integration breaks, and the audit trail shows a person who did not make the calls.
Tokens expire. Your client must handle a 401 response by requesting a new token and retrying once. This matters for the retry logic covered later in the tutorial.
Outbound: the problem Named Credentials solve
Without Named Credentials, a callout might look like this:
req.setEndpoint('https://billing.example.com/api/invoices/1');
req.setHeader('Authorization', 'Bearer eyJhbGciOi...');This has four problems:
- The secret is in source code, version control, and debug logs.
- The hostname differs between sandbox and production, so you edit code for each deployment.
- You must add the host to Remote Site Settings.
- You write your own token refresh logic, and every developer writes it differently.
A Named Credential removes all four. Your code uses a logical name, and Salesforce supplies the host and the credentials at runtime:
req.setEndpoint('callout:Billing_API/invoices/1');Salesforce replaces callout:Billing_API with the configured URL. It also adds the authentication, and it refreshes tokens where the protocol supports it. Callouts through a Named Credential do not need a Remote Site Setting entry.
The current model: three linked records
Salesforce now splits the old single record into three parts. The split is the most common source of confusion, so learn what each part holds.
| Record | Holds | Changes between sandbox and production? |
|---|---|---|
| Named Credential | Base URL, a link to an External Credential, callout options | Yes (different hosts) |
| External Credential | Authentication protocol, and one or more principals | Often (different client IDs) |
| Principal | The identity used for the call: either one shared identity or one per user | Secret values are entered per org |
A principal is the identity Salesforce uses when calling out. It comes in two kinds:
- Named principal. One shared identity for all callers. All Salesforce users who can use the principal make calls as the same external account. This fits system-to-system integrations such as billing lookups.
- Per-user principal. Each Salesforce user authenticates separately, often through an OAuth consent screen. The external system then sees the real user. This fits cases where the external system enforces per-person permissions.
The External Credential supports several protocols. These include OAuth 2.0 (browser flow, JWT bearer, client credentials), AWS Signature Version 4, basic authentication, and custom authentication where you supply headers yourself.
Granting access: the permission set step
The new model adds a step that many developers miss. Having the Named Credential is not enough to call it. The running user must have a permission set that grants External Credential Principal Access for the principal. If this is missing, the callout fails even though the configuration is correct.
A typical setup sequence:
- Create the External Credential and choose its protocol.
- Add a principal and enter the secrets (client secret, password, or private key reference).
- Create the Named Credential with the base URL and link it to the External Credential.
- Create or update a permission set and enable the principal under External Credential Principal Access.
- Assign the permission set to the user who runs the Apex code.
Think about who the running user is. A synchronous callout from a button click runs as the person who clicked. A scheduled Apex job runs as the user who scheduled it. A platform event trigger runs as the Automated Process user unless you configure otherwise. Each of those users needs the permission set, or the callout fails only in some contexts.
Using the Named Credential in Apex
This is the request-reply callout from the plan, now with the authentication pieces in view.
public with sharing class InvoiceClient {
public static String fetchInvoiceStatus(String invoiceId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/invoices/' + EncodingUtil.urlEncode(invoiceId, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(10000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('status');
}
throw new CalloutException('Billing API returned ' + res.getStatusCode());
}
}Points to notice:
- The code contains no host name, token, or password. The same class deploys unchanged from a sandbox to production.
- You never set an
Authorizationheader. Salesforce adds it. If you set one yourself, you create a conflict and bypass the point of the feature. - The path after the name (
/invoices/...) is appended to the base URL of the Named Credential. If the base URL ishttps://billing.example.com/api, the full request goes tohttps://billing.example.com/api/invoices/.... EncodingUtil.urlEncodeprotects the path from characters in the ID that would change the URL's meaning.
Testing without a real endpoint
Apex tests cannot make real callouts. Mock the response. The mock sees the callout: form of the endpoint, so you can assert on it.
@IsTest
private class InvoiceClientTest {
private class BillingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
System.assertEquals('GET', req.getMethod());
System.assert(req.getEndpoint().startsWith('callout:Billing_API/invoices/'));
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"status":"PAID"}');
return res;
}
}
@IsTest
static void returnsStatusFromBillingApi() {
Test.setMock(HttpCalloutMock.class, new BillingMock());
Test.startTest();
String status = InvoiceClient.fetchInvoiceStatus('INV-1');
Test.stopTest();
System.assertEquals('PAID', status);
}
}Legacy Named Credentials
Older orgs may still have the original single-record Named Credential. It stores the URL and the identity settings in one place. Apex code uses the same callout: syntax, so your code does not change when you migrate. The differences are in setup:
| Aspect | Legacy | Current |
|---|---|---|
| Records | One Named Credential | Named Credential, External Credential, principals |
| Who may use it | Anyone who can run the code | Users with principal access through a permission set |
| Header values | Merge fields such as `{!$Credential.Username}` | Formulas that reference the External Credential's values |
| Recommended for new work | No | Yes |
When you maintain existing code, check which model the org uses before you debug. A permission error on a legacy credential has a different cause than the same error on a current one.
Common errors
- "Unable to find named credential" or a similar message. The name in
callout:is wrong. It is case-sensitive in practice and must match the developer name, not the label. - Callout works for you but fails for a scheduled job or a trigger. The user running the job lacks principal access. Assign the permission set to that user.
401from the external system. The token or secret is wrong, expired, or lacks the scope the API needs. Check the principal's credentials and the external client's configuration.- "You have uncommitted work pending." You made a DML change and then a callout in the same transaction. Do the callout first, or move one of them into asynchronous Apex.
- Hand-set
Authorizationheader. It overrides or conflicts with the managed one. Remove it. - Different secrets in sandbox and production. Secrets are not deployed with metadata. After you deploy, enter them again in each org, and make that a documented release step.
Security checklist
- Use the least privileged scopes and permission sets that let the integration work.
- Use a dedicated integration user for inbound calls, and keep its permission set narrow.
- Prefer JWT bearer or client credentials for unattended jobs, and rotate secrets on a schedule.
- Prefer a named principal for system integrations and a per-user principal only when the external system must know the person.
- Keep host names in the Named Credential, not in custom settings or constants.
- Restrict who can edit the External Credential. Whoever can change the base URL could redirect authenticated traffic to a host they control.
Exercise
An Apex class calls callout:Billing_API/invoices/42. It works when an admin runs it from Developer Console, but a nightly scheduled job that runs the same method fails with a permission error on the credential. The Named Credential URL and secrets are correct. What is the most likely cause and the fix?
Show answer
The user who scheduled the job has no permission set granting External Credential Principal Access for the Billing_API principal. Named Credential configuration being correct is not enough, because in the current model each running user needs principal access. The admin's own permissions explain why the manual run works. Assign the permission set to the user running the scheduled job, then run the job again.
Exercise
A teammate adds req.setHeader('Authorization', 'Bearer ' + token) to a callout that already uses a Named Credential, with the token stored in a custom setting. Give two reasons to remove it.
Show answer
First, the secret is now stored in a custom setting and passes through code and potentially logs, which the Named Credential was meant to prevent. Second, Salesforce already supplies and refreshes the authentication, so a hand-set header duplicates or conflicts with the managed one, and the token will not be refreshed when it expires.