Sub topic 14
Moving credential metadata between orgs
This chapter assumes you can run Salesforce CLI deployments or use change sets. It also assumes you have built a Named Credential, an External Credential and a permission set, as covered in earlier chapters. You should know what a principal is.
The goal is to promote a working callout setup from a sandbox to UAT and production without copying secrets by hand into source control. The setup is split across several metadata types. Some parts deploy cleanly, and some parts can never deploy.
What deploys and what does not
The callout setup spans four kinds of metadata. Only the secret values are excluded.
| Piece | Metadata type | Deploys? | Notes |
|---|---|---|---|
| Endpoint URL, callout options, custom headers | `NamedCredential` | Yes | Header formulas deploy as text. |
| Authentication protocol, principals, parameter names | `ExternalCredential` | Yes | The structure deploys. Secret values do not. |
| Who may use a principal | `PermissionSet` | Yes | Stored as `externalCredentialPrincipalAccesses`. |
| OAuth provider settings | `AuthProvider` | Yes, with caveats | Client secrets must be re-entered in the target org. |
| API keys, passwords, tokens | Stored values | No | You enter them in the target org's Setup. |
| Per user tokens | Stored values | No | Each user authenticates again in the target org. |
The Apex class WeatherService needs no changes between orgs. It refers to callout:Weather_API, which is a name, not a URL or a secret. The Named Credential in each org decides where that name points.
Retrieving the metadata
List every type in a manifest so one deployment carries the whole setup. The package.xml below retrieves the Named Credential, the External Credential and the permission set from the outline in this tutorial:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>Weather_EC</members>
<name>ExternalCredential</name>
</types>
<types>
<members>Weather_API</members>
<name>NamedCredential</name>
</types>
<types>
<members>Weather_Callout_Access</members>
<name>PermissionSet</name>
</types>
<types>
<members>WeatherService</members>
<members>WeatherServiceTest</members>
<name>ApexClass</name>
</types>
<version>62.0</version>
</Package>Retrieve it and deploy it with the Salesforce CLI:
sf project retrieve start --manifest manifest/package.xml --target-org devsandbox
sf project deploy start --manifest manifest/package.xml --target-org uatIncluding the Apex classes, the credentials and the permission set in one manifest avoids ordering problems. The deployment resolves references among the components in the package. If you split them up, deploy the External Credential first, then the Named Credential that references it, then the permission set that references the principal.
What the permission set file contains
The permission set stores the grant as an entry named after the External Credential and the principal, joined with a hyphen. A retrieved Weather_Callout_Access.permissionset-meta.xml contains this entry:
<externalCredentialPrincipalAccesses>
<enabled>true</enabled>
<externalCredentialPrincipal>Weather_EC-Weather_Principal</externalCredentialPrincipal>
</externalCredentialPrincipalAccesses>This entry grants access to the principal. It does not supply the secret. Users in the target org get the grant once the permission set deploys and is assigned to them. The callout still fails until someone enters the secret on the principal.
Handling the URL for each environment
The Named Credential stores the endpoint URL, and that URL often differs per environment. A sandbox might call https://sandbox.api.example.com/v1, and production calls https://api.example.com/v1. If you deploy the retrieved file unchanged, the target org points at the source org's URL.
You have three options:
- Edit the file before each deployment. This is simple, and it is easy to forget.
- Use string replacements in the Salesforce CLI. The deployment substitutes a value from an environment variable, so the committed file stays the same.
- Deploy once, then edit the Named Credential in Setup. This works for one-off moves. It leaves drift between source control and the org.
Option 2 is configured in sfdx-project.json:
{
"packageDirectories": [{ "path": "force-app", "default": true }],
"sourceApiVersion": "62.0",
"replacements": [
{
"filename": "force-app/main/default/namedCredentials/Weather_API.namedCredential-meta.xml",
"stringToReplace": "https://sandbox.api.example.com/v1",
"replaceWithEnv": "WEATHER_API_URL"
}
]
}Set the variable before you deploy. In a CI pipeline, store the value in the pipeline's configuration for each environment:
export WEATHER_API_URL="https://api.example.com/v1"
sf project deploy start --manifest manifest/package.xml --target-org productionThe replacement happens during deployment. The project files on disk are not changed.
Entering secrets after the deployment
After the deployment, the External Credential exists and its principal exists, but the principal holds no secret. Complete these steps in the target org:
- Open Setup, then Named Credentials, then the External Credentials tab, and open
Weather_EC. - In the Principals section, open
Weather_Principaland choose Edit Authentication Parameter. For a named principal using the Custom protocol, enter theApiKeyvalue. - Confirm that the permission set is assigned to the users or to a permission set group that includes it.
For an OAuth 2.0 protocol, you also need to re-enter the client ID and client secret on the authentication provider. A person with the right access then authenticates the named principal. For a per user principal, each user opens their own Authentication Settings for External Systems page and authenticates in the target org. Plan for this before go-live. Users who authenticated in the sandbox are not authenticated in production.
Sandbox refreshes and copied settings
A sandbox refresh or clone copies the metadata from the source org. After a refresh, check the following before anyone runs a callout:
- The Named Credential URL. A sandbox copy of production metadata can point at the production service, so a test run could call the real system.
- The stored secrets. Treat any secret that carried over from production as something to replace with a sandbox key. Confirm what your org actually kept.
- The authentication provider's callback URL. It contains the org's domain, so the external OAuth app must list the new callback URL.
Validating the deployment
Deploying to production requires Apex tests to pass. WeatherServiceTest uses Test.setMock, so it needs no credentials and no network access. A passing test therefore says nothing about whether the credential is configured correctly. Validate the credential separately with a callout that does not change data. One option is an anonymous Apex snippet that calls a read-only endpoint:
String body = WeatherService.getForecast('Oslo');
System.debug(body);Run it as a user who has the permission set. Running it as an administrator without the grant fails, even when the secret is correct. If it fails, check the sequence in this order:
- The URL in the Named Credential for that org.
- The secret on the principal.
- The permission set assignment for the running user.
- For per user principals, whether that user has authenticated.
Common deployment problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Deployment fails: the principal does not exist | The permission set deployed without the External Credential. | Add `ExternalCredential` to the manifest. |
| Callout hits the wrong host | The Named Credential URL was copied from the source org. | Use a replacement or edit the URL in the target org. |
| Callout returns 401 after a successful deployment | The principal has no secret in the target org. | Enter it in Setup. |
| Access error for one user only | The permission set is not assigned, or the per user token is missing. | Assign the permission set and ask the user to authenticate. |
Keeping the setup repeatable
- Keep the manifest in source control next to the Apex it supports.
- Document the manual steps (secrets, authentication) as a release checklist. The deployment cannot do them for you.
- Use the same API names for the External Credential, principal and permission set in every org. The
callout:name and the permission set grant depend on these names. - Give each environment its own key where the provider allows it.
Exercise
You deployed Weather_EC, Weather_API and Weather_Callout_Access to UAT with one manifest. The deployment succeeded and the user has the permission set. The callout still returns 401. What did the deployment leave out, and where do you fix it?
Show answer
Secret values are never part of retrieved or deployed metadata. The principal Weather_Principal in UAT has no ApiKey yet. Enter it in Setup under the External Credential's principal, using Edit Authentication Parameter. After that, run the callout again as a user who has the permission set.
Exercise
Your sandbox Named Credential points at https://sandbox.api.example.com/v1, and production must point at https://api.example.com/v1. Describe how to deploy the same source files to both without editing them by hand.
Show answer
Add a replacements entry in sfdx-project.json for the Named Credential file. Set stringToReplace to the sandbox URL and replaceWithEnv to a variable such as WEATHER_API_URL. Set the variable to the target environment's URL before running sf project deploy start. The committed file stays unchanged.