Sub topic 3
Custom Headers and Credential Formulas
Assume you know basic Apex callouts, HTTP headers, OAuth 2.0, and permission sets. Salesforce stores authentication settings separately from the Apex code that uses them.
Custom headers and formulas
A custom header sends a value such as an API key with each request. Store the secret in an External Credential authentication parameter, then reference it from the Named Credential.
public with sharing class WeatherService {
public static HttpResponse getForecast(String city) {
HttpRequest request = new HttpRequest();
request.setEndpoint(
'callout:Weather_API/forecast?city=' +
EncodingUtil.urlEncode(city, 'UTF-8')
);
request.setMethod('GET');
return new Http().send(request);
}
}Configure the Named Credential with a custom header named X-Api-Key and value {!$Credential.Weather_EC.ApiKey}. Salesforce resolves the formula when it sends the request.
OAuth and per-user authentication
For OAuth 2.0, create an Authentication Provider with the external system's authorization and token endpoints. Select that provider in the External Credential and define the required scopes.
Use a named principal when one service identity should access the API for all users. Use a per-user principal when every Salesforce user must authorize separately. Per-user authentication gives the external service each user's identity, but it requires an authorization flow for each user.
Troubleshooting and deployment
Common failures have different causes:
- A
401or403usually means an invalid token, missing scope, expired authorization, or missing principal access. - A URL error often means the Apex endpoint does not use the correct Named Credential name.
- A missing header can indicate an incorrect credential formula or an unset authentication parameter.
- Tests must use
HttpCalloutMock; they cannot contact the real service.
Deploy the Named Credential, External Credential, principals, and permission-set metadata, then configure secrets and authorize users separately in each org. Do not assume production has the same secret as a sandbox.
Legacy credentials and security
Legacy Named Credentials combine the service URL and authentication settings. Newer Named Credentials separate the URL from External Credentials, which supports multiple principals and clearer access control. Migrate deliberately and retest every callout.
Grant only the required principal access. Keep secrets out of Apex, debug logs, source control, and error messages. Use narrow OAuth scopes, rotate keys, and review permission sets regularly.
Exercise
When should you choose a per-user principal instead of a named principal?
Show answer
Choose it when the external service must identify and authorize each Salesforce user separately.