Sub topic 2
Why credentials should not live in Apex code
This chapter assumes you can read basic Apex, know what an HTTP request, header and status code are, and can find your way around Setup. You should also know in outline what an API key, Basic authentication and OAuth 2.0 are. The chapter explains the problem that Named Credentials and External Credentials solve. The later chapters cover how to configure them.
The tempting first version
The quickest way to call an external API from Apex is to put everything in the class: the URL, the key, and the header that carries it.
public with sharing class WeatherServiceNaive {
private static final String BASE_URL = 'https://api.example.com/v1';
private static final String API_KEY = 'sk_live_51Hxxxxxxxxxxxx';
public static String getForecast(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint(BASE_URL + '/forecast?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setHeader('X-Api-Key', API_KEY);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Weather API returned status ' + res.getStatusCode());
}
return res.getBody();
}
}This works, and that is why it is dangerous. It passes review, passes tests with a mock, and runs in production. The problems appear later, and they fall into three groups: security, operations and platform behavior.
Security problems
The secret is stored with the code
An Apex class is source code. It is copied to version control, pasted into pull requests, shared in screenshots, and retrieved to developers' laptops. Once the key is in a Git commit, it stays in the history even after you delete the line. Any person or tool that can read the repository can read the key.
In the org itself, anyone who can view Apex classes can read the string. In a sandbox, that often means every developer and consultant on the project. A sandbox copy of production also copies the class, and with it the live key.
Secrets spread to the places that handle code
The key does not stay in one file. It can end up in:
- Static analysis reports and CI logs that quote the offending line.
- Backups, sandbox refreshes and scratch org definitions.
- Error messages, if you build a string that includes the request and write it to a log or an exception.
Each copy is another place to leak from, and you cannot recall them all when you need to rotate the key.
Storing the secret elsewhere in Salesforce only moves the problem
A common second attempt is to move the key to a custom label, a custom setting or custom metadata. This removes the literal from the class, but the value is still readable by Apex and, depending on configuration, by users and administrators. Custom settings and custom metadata are also easy to export, deploy and include in a sandbox copy. You are now responsible for protecting the storage, restricting who can query it, and keeping it out of deployments. The platform has a feature built for this purpose, so you do not need to design that protection yourself.
Operational problems
Rotating a key needs a deployment
Keys expire, staff leave, and vendors force resets. If the key is a literal, rotation means editing a class, running tests, and deploying through your release pipeline. That is slow when you most need speed, such as after a suspected leak. With a credential stored in Setup, an administrator updates one value and no code changes.
Each environment needs different values
Production, a full sandbox and a developer sandbox usually talk to different endpoints with different keys. With literals you either keep several versions of the class or write branching logic:
Boolean isSandbox = [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;
String baseUrl = isSandbox ? 'https://sandbox.api.example.com/v1' : 'https://api.example.com/v1';This is extra code, an extra query, and one more place for production to point at the wrong system. It also means the sandbox class differs from the production class, so you are not testing what you ship.
OAuth tokens need a lifecycle
An API key is a single static value, which is the easy case. With OAuth 2.0 the access token expires, often within an hour, and something has to request a new one using a refresh token or client credentials. If you write this yourself, you need to store the tokens somewhere (see above), handle expiry and failed refreshes, and avoid two concurrent transactions refreshing at once. Getting this wrong produces intermittent 401 responses that are hard to reproduce.
Platform problems
Each endpoint needs a Remote Site Setting
Apex blocks callouts to a URL unless the site is registered. With a hardcoded endpoint, you must create a Remote Site Setting for every host you call. A forgotten entry shows up at runtime as an Unauthorized endpoint error. This check is a separate piece of configuration that has to stay consistent with the URL in your code.
Access to the secret is all or nothing
If the key is in the class, anyone who can run that class can make authenticated calls to the external system. You cannot say "sales users may call this API but support users may not" without writing your own checks in Apex. Those checks are easy to skip when someone adds a second entry point to the same class.
Per-user identity is not possible
Some APIs should be called as the individual user, so the external system sees who did what and applies that user's permissions. A shared key in code cannot do this. Every call looks like the same caller.
What the platform provides instead
Salesforce splits the problem into pieces, each with one job. This chapter only names them. Later chapters build each one.
| Concern | Hardcoded in Apex | Handled by the credential model |
|---|---|---|
| Where the service lives | String literal in the class | Named Credential holds the URL |
| How you authenticate | Header set in code | External Credential defines the protocol and stores the secret |
| Who may use it | Anyone who can run the class | Permission sets grant access to a principal |
| Rotating a secret | Code change and deployment | Update the value in Setup |
| Remote Site Setting | Required per host | Not needed for callouts through a Named Credential |
| OAuth token refresh | Written and maintained by you | Performed by the platform |
The Apex side shrinks to the endpoint and the business logic:
public with sharing class WeatherService {
public static String getForecast(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Weather_API/forecast?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Weather API returned status ' + res.getStatusCode());
}
return res.getBody();
}
}The endpoint begins with callout: and the name of a Named Credential, Weather_API. At run time Salesforce replaces that prefix with the base URL, applies the authentication, and sends the request. The class has no URL, no key, and no X-Api-Key header.
Edge cases and limits of this approach
A Named Credential removes the secret from your code. It does not make every other risk disappear.
- Callout rules still apply. The governor limits on callouts, timeouts and response size are the same. You also still cannot make a callout while uncommitted DML is pending in the same transaction.
- Access is a separate task. A correct Named Credential does not help a user who has not been granted access to its principal through a permission set. This is the source of many "it works for me but not for them" reports and is covered later.
- You can still leak the response. If the external API returns sensitive data and you log or store it carelessly, the credential model does not protect you.
- Existing integrations use an older model. Orgs created before the current model may use legacy Named Credentials, which combine the URL and authentication in one record. The
callout:syntax is the same, so Apex code looks identical, but the setup differs. - Tests are unaffected. Apex tests cannot make real callouts either way, so you still use
HttpCalloutMock. The mock can check that the endpoint starts withcallout:Weather_API/, which helps catch a developer who reintroduces a literal URL.
A practical rule
Treat any string in Apex that you would be unhappy to see in a pull request, screenshot or ticket as a defect. That includes API keys, passwords, client secrets, bearer tokens and production URLs that differ per environment. During code review, search for setHeader('Authorization', setHeader('X-Api-Key', https:// and Blob.valueOf( used with an encoded username and password. Each hit is either a candidate for a Named Credential or should have a clear reason to stay.
Exercise
A teammate moves the API key from the Apex class into a custom label and says the problem is solved. Give two reasons this is not equivalent to using an External Credential, and say what you would check in the class to confirm the callout is using a Named Credential.
Show answer
The secret is still readable by Apex and by users or administrators with access to labels, and it still travels with exports, deployments and sandbox copies. Also, the code must still set the authentication header itself, still needs a Remote Site Setting, and gives no per-permission-set control over who can use the key. To confirm Named Credential use, check that the endpoint passed to setEndpoint starts with callout: followed by the Named Credential name, and that no code sets the Authorization or key header.
Exercise
Name three operational problems caused by hardcoding a URL and key in a class that are removed when the secret is held in Setup.
Show answer
Rotating the key no longer needs a code change and deployment. Different environments can use different endpoints and keys without branching logic or different class versions. For OAuth, the platform handles token expiry and refresh instead of custom code. Remote Site Setting maintenance also goes away for the endpoint.