Sub topic 16
Security practices and least privilege
This chapter assumes you can already build a callout with a Named Credential, an External Credential, a principal and a permission set. It also assumes you know the callout: endpoint syntax. Here the question changes from "does it work?" to "who can use it, what can they do with it, and what happens if something leaks?"
Where the risk sits
Named Credentials remove the most common mistake, which is a secret in Apex code, a custom setting or a Remote Site Setting. They don't remove every risk. Four places still need attention:
- The secret itself: where it is stored and who can change it.
- Who can trigger callouts that use it.
- What the Apex code lets a caller send to the external service.
- What the credential is allowed to do on the external system.
Least privilege means narrowing each of these to the smallest scope that still lets the integration work.
Keep the secret where Salesforce put it
Secrets belong in the External Credential, as authentication parameters or OAuth settings entered in Setup. Salesforce stores them encrypted. After you save one, you can't read it back.
- Don't put keys in Apex, custom labels, custom metadata, custom settings or static resources.
- Don't commit secrets to source control. Metadata deployments carry the structure of External and Named Credentials, not the secret values. After a deployment, someone with the right Setup access enters the secret in each org. Sandboxes should use a separate, low-value key, not the production key.
- Rotate by editing the parameter in Setup. No code deployment is needed. This is a real advantage over hardcoded keys, so write a rotation schedule and use it.
- Put secrets in a header, not the query string. Query strings are often written to web server and proxy logs. A header such as
X-Api-Keyis much less likely to be.
Restrict who can edit credentials too. Changing the URL of a Named Credential to a host you control would send the injected authorization header to that host. Treat the ability to edit credentials as an administrator privilege. Setup Audit Trail records those changes, so review it.
Grant access with narrow permission sets
A user can only make a callout through an External Credential if one of their permission sets lists the principal under External Credential Principal Access. This is the main control over who can use the credential.
Follow these rules:
- Create one permission set per integration, for example
Weather_Callout_Access. Don't add principal access to a broad profile-like permission set such as "Sales User". - Name the permission set after the integration, so an audit shows quickly what each one grants.
- Assign it to the people or automation that need it. Use permission set groups only when the group's purpose matches the integration.
- Review assignments regularly. Remove users who changed roles.
The running user is the one whose access is checked. That includes automated contexts. A Queueable job, a batch job and a scheduled job each run as a particular user, and that user needs the access. Platform event triggers run as the Automated Process user by default, which usually has no principal access. If an integration fails only in async or event-driven runs, check this first.
Choose the principal type for the risk
The principal type decides whose identity the external system sees.
| Aspect | Named principal | Per user principal |
|---|---|---|
| Identity at the external system | One shared account | Each user's own account |
| Who stores the secret | An admin, once, in Setup | Each user authenticates themselves |
| Audit trail on the external side | Shows only the shared account | Shows the individual user |
| Permissions on the external side | Same for everyone who has access | Follow each user's rights there |
| Main risk | Anyone with access acts with the shared account's full rights | Users who haven't authenticated get errors |
| Good fit | System-to-system data sync, public APIs | Actions on a person's own data, such as their calendar or files |
With a named principal, Salesforce permission sets are the only thing standing between a user and the shared account's rights. So the shared account on the external side must have only the rights the integration needs. A read-only API key for a read-only integration is much safer than an admin key. If the external system supports scopes, request only the scopes the integration uses. Use a dedicated integration account, never a person's account, so it keeps working when staff leave.
Limit what the Apex code exposes
The callout runs with the credential's rights, whoever asks for it. Apex that exposes the credential too broadly lets any user with access to that code borrow those rights. Compare two designs:
- A generic method such as
send(String path, String method, String body)that any caller can use. This hands out the shared identity for any request. - A narrow method such as
getForecast(String city)that builds one kind of request from validated input.
Prefer the narrow design. Keep the code that calls out in a service class, and validate input in whatever layer faces users:
public with sharing class WeatherForecastController {
@AuraEnabled
public static String forecast(String city) {
if (String.isBlank(city) || !Pattern.matches('[A-Za-z ]{1,60}', city)) {
throw new AuraHandledException('Enter a city name using letters and spaces only.');
}
return WeatherService.getForecast(city);
}
}The WeatherService class from earlier in the tutorial encodes the value with EncodingUtil.urlEncode before adding it to the endpoint. Encoding and validation do different jobs. Validation rejects input you don't expect. Encoding stops input that slipped through from changing the structure of the URL. Use both. Never let a caller choose the host or the path prefix. The Named Credential fixes the host, so keep it that way and only let callers supply parameter values.
Also check what you return. The service in this tutorial throws a CalloutException that includes the status code only. It leaves out the response body. Error bodies can contain internal details, tokens or personal data. Log the body only if you've decided that is safe, and don't send it to the browser.
Keep secrets out of logs and tests
- Don't call
System.debugon request headers, request bodies or response bodies that hold sensitive data. Debug logs can be read by anyone with the right permission, and they can be kept for days. - With a
callout:endpoint, injected headers don't appear in your Apex objects.req.getHeader('X-Api-Key')returns nothing for a header Salesforce adds later. Don't try to read it, and don't add a copy of the key to make debugging easier. - Use fake values in test data and mocks. The
HttpCalloutMockin the earlier chapter returns a fixed body like{"temp":21}. Keep real data and real keys out of test classes.
Review formulas and header settings
Custom headers can use credential formulas such as {!$Credential.Weather_EC.ApiKey}. Only enable the formula options you need on the Named Credential. Check the settings that control whether formulas are allowed in headers or bodies. Each formula option enlarges what an editor of the Named Credential can do with the secret. Packages add another case. If a managed package makes callouts through your credential, look at the Named Credential's namespace restrictions and allow only the namespaces that need access.
How the checks stack up
Each layer can fail independently, so build every one of them. Don't rely on the external system to catch a mistake made in Salesforce, or the reverse.
A review checklist
Use this list for each integration before it goes live and again every few months:
- The secret exists only in Setup, and someone owns its rotation date.
- The external account or key has the minimum scopes and is dedicated to the integration.
- One permission set grants principal access, and only the needed users or automation have it.
- Apex exposes narrow methods, validates input and never lets callers choose the host.
- Logs, error messages and tests contain no secrets or sensitive response data.
- Formula options and namespace settings on the Named Credential are as tight as the integration allows.
- Sandboxes use separate credentials from production.
Exercise
A scheduled Apex job calls an external API through a Named Credential with a named principal. It works when an administrator runs the code from Anonymous Apex, but fails as a scheduled job. The schedule was created by a user whose permission sets don't include the principal. Give the cause and a least-privilege fix.
Show answer
Principal access is checked for the user the job runs as, and the scheduling user has no access. The administrator's manual run worked because the administrator has it. The least-privilege fix is to add the integration's dedicated permission set, which lists the External Credential principal, to the user who schedules the job, or to a dedicated integration user who owns the schedule. Don't add the principal to a broad permission set or give the user admin rights, and don't move the secret into code.
Exercise
Your team wants one Apex method, callApi(String url, String method, String body), used by all components. Name two security problems and the safer design.
Show answer
First, any caller can send arbitrary requests with the shared identity, so a user with access to the method gains every right the credential has on the external system. Second, a caller-supplied URL or path can reach endpoints the integration never meant to touch, or inject unexpected parameters. The safer design is a service class with narrow methods such as getForecast(String city). Each builds one kind of request on the callout: endpoint, validates and URL-encodes its inputs, and is covered by a single permission set.