ServicesSalesforce consultingArchitectureImplementationOrg health checkDevelopmentIntegrations and APIsData migrationTesting and QAManaged supportSpecialist supportMarketing Cloud auditDeliverability
SolutionsMarketing Cloud EngagementMarketing Cloud NextSalesforce + BrazeAccount EngagementData Cloud (Data 360)Identity resolutionInsights and segmentsAgentforce and AIMCP integrationsSales and Service CloudReal-time personalisationIntegration solutionsEnterprise AI integrationBy industry
ArchitectureSalesforce CRMData 360Salesforce + BrazeAgentforceCustomer 360API-led integrationEvent-drivenMCP host, client and serverIdentity and consentMCP securityData governanceCI/CD and releasesOur public MCP server
ResourcesEngineering journalDecision guidesSolution blueprintsSalesforce productsProjects and achievementsSales ROI calculatorWhere we workChecklists and templatesPlanning toolsReadiness assessmentGlossaryAbout GeekMidstOur approachOur expertiseContact
CompanyAbout GeekMidstOur approachDelivery methodologyTrust and evidenceProjectsAchievementsBook a consultationContactWhere we workSecurity and data
Book a Consultation

Named and External Credentials, Explained

Named Credentials hold the endpoint, External Credentials hold the authentication, and permission sets decide who can use them. Here is how the pieces fit together.

Type
Article
Topic
CRM & Engineering
Reading time
5 min
Updated
Author
GeekMidst Team
Reviewed by
Site owner
Data protection officer filing consent forms into coloured folders as an architect checks a timeline

Hard-coded endpoints and API keys in Apex, custom settings or custom metadata are still common in Salesforce orgs. They leak into sandboxes, appear in debug logs and get copied into source control. Named Credentials exist to stop that: they keep the URL and the secrets in Setup, out of your code, and the platform adds authentication to the callout for you.

Since Salesforce redesigned the feature, setting one up involves two objects instead of one, plus permission sets. The split confuses people the first time, so this guide explains what each piece does.

Diagram showing Apex and flows calling a Named Credential, which uses an External Credential and its principal, granted through a permission set, to authenticate a callout to an external API
The Named Credential holds the endpoint, the External Credential holds authentication, and a permission set must grant the running user its principal. View full size

The pieces and what they hold

Named Credential. The endpoint: a base URL and callout options such as whether to generate an authorisation header and whether formulas are allowed in headers. Code refers to it by name with the callout: prefix. A Named Credential points to one External Credential.

External Credential. How to authenticate: the protocol and its settings. Options include OAuth 2.0 flows, AWS Signature Version 4 and a custom protocol where you define your own parameters and headers, such as an API key. Check Salesforce Help for the full current list. One External Credential can be shared by several Named Credentials that use the same login, for example separate endpoints on the same vendor platform.

Principal. The identity used for the callout, defined on the External Credential. A named principal is one shared identity for everyone, typical for system-to-system integrations. A per-user principal means each user authenticates with their own account, typical when the external system must see who is acting.

Permission set access. Users, including integration and automation users, only get to use a principal if a permission set or permission set group grants access to it. This is the step most often missed.

Legacy Named Credentials. The older model combined endpoint and authentication in one record. It still works in many orgs, but new work should use the current model.

Who holds what

HoldsConfigured byReferenced from
Named CredentialURL and callout optionsAdmin or developerApex, flows, External Services
External CredentialProtocol, parameters, principalsAdmin with security inputNamed Credentials
PrincipalIdentity and its secretsAdmin, or each user for per-userPermission sets
Permission setAccess to principalsAdminAssigned users

Setting up an API key integration

  1. 01

    Create the External Credential

    Choose the custom protocol, then add a named principal and store the API key as an authentication parameter on it.

  2. 02

    Add the header

    Define a custom header, for example X-Api-Key, whose value is a formula referencing the principal's parameter. Help documents the $Credential merge syntax for this.

  3. 03

    Create the Named Credential

    Set the base URL, link it to the External Credential and enable formulas in headers so the header formula is evaluated.

  4. 04

    Grant access

    Add the External Credential principal to a permission set and assign it to the users or integration user who run the callout. Check Help for any related object permissions that users also need.

  5. 05

    Call it from code

    Use callout: followed by the Named Credential name in the endpoint, and test in a sandbox with a sandbox key.

Calling a Named Credential from Apex

Assumptions

A Named Credential called Shipping_API whose URL is the vendor's base address, with authentication handled by its External Credential. The vendor returns JSON with a numeric rate field. The code is illustrative and leaves out logging and retries.

apex
public with sharing class ShippingRateClient {

    public class ShippingApiException extends Exception {}

    public static Decimal fetchRate(String postcode) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:Shipping_API/v1/rates?postcode='
            + EncodingUtil.urlEncode(postcode, 'UTF-8'));
        req.setMethod('GET');
        req.setTimeout(10000);

        HttpResponse res = new Http().send(req);
        if (res.getStatusCode() != 200) {
            throw new ShippingApiException(
                'Rate lookup failed with HTTP ' + res.getStatusCode());
        }

        Map<String, Object> body =
            (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
        return Decimal.valueOf(String.valueOf(body.get('rate')));
    }
}
No URL or key in code. The platform resolves callout:Shipping_API and adds the authentication header.

Because the endpoint is resolved by name, the same code works in every environment. Each sandbox has its own Named Credential and External Credential values pointing at the vendor's test environment, and production points at the live one. After a sandbox refresh, review these records: the configuration copies from production, but secrets may need re-entering and you do not want a sandbox calling a live endpoint.

Common mistakes and how to diagnose them

  • Callout fails with an authentication or permission error for some users only. The user lacks a permission set granting the principal, or the per-user principal has not been authenticated by that user.
  • Works in a test, fails from a flow or scheduled job. The automation runs as a different user (an integration user, or the Automated Process user for some async contexts) that has not been granted access.
  • Header formula sent literally. Formulas in headers are not enabled on the Named Credential, or the merge syntax is wrong.
  • Secrets in source control anyway. Named Credential metadata can be deployed, but secret values are not part of it. Keep it that way; enter secrets per environment.
  • Unit tests make real callouts. Apex tests cannot make callouts; use HttpCalloutMock to simulate the response.

Security checklist

  1. No endpoints or secrets in Apex, custom settings or custom metadata.
  2. Named principals for system integrations, per-user principals where the external system must know the user.
  3. Access to principals granted through a dedicated permission set, assigned only to those who need it.
  4. Separate credentials for sandboxes and production, reviewed after every refresh.
  5. OAuth scopes and API keys limited to what the integration needs.
  6. A named owner and a rotation date for each secret.

Workflow diagram

Explore how the pieces fit together. Select a step to read what happens there.

Architecture

API integration architecture

Open full size
API integration architectureA client calls an API gateway or middleware layer, which checks the token and forwards valid requests to Salesforce APIs. Flow or Apex logic runs, calls the system of record through a named credential, and the result is returned to the client.API integration architectureClientAPI gatewaySalesforceSystem ofrecordYesNoClient request: Web, mobile or partner app. The client sends a request with an access token and a correlation ID, so the call can be traced through every system it touches.Client requestWeb, mobile orpartner appGateway or middleware: Auth, rate limits. A gateway or middleware layer such as MuleSoft gives clients one stable API, applies rate limits and shapes payloads, so clients are not tied to Salesforce internals.Gateway ormiddlewareAuth, rate limitsToken valid?. Check the token, its scopes and the client identity before anything reaches Salesforce. Each client should have its own credentials so access can be revoked separately.Token valid?Request rejected: Clear error code returned. Return a clear 401 or 403 with no internal detail. Log the attempt; repeated failures from one client are worth an alert.Request rejectedClear error codereturnedSalesforce API: REST, Composite or Bulk. Pick the API for the job: REST for single records, Composite to group related calls, Bulk for large volumes. The wrong choice shows up as API limit pressure.Salesforce APIREST, Composite orBulkBusiness logic: Flow or Apex rules. Business rules run inside Salesforce with the integration user's permissions. Give that user only the objects and fields the integration needs.Business logicFlow or Apex rulesNamed credential: Stored auth for callouts. Outbound calls use a named credential and external credential, so endpoints and secrets are not written into code and can be rotated without a deployment.Named credentialStored auth forcalloutsSystem of record: ERP, billing, core. The system that owns the data applies the change or returns it. Agree which system is the master for each field to avoid two systems overwriting each other.System of recordERP, billing, coreResponse sent: Result plus correlation ID. The client gets the result, or a clear error, along with the correlation ID for support. Keep response shapes stable when versions change.Response sentResult plus correlationIDStartSystem or platformDecisionAlert or exceptionProcess stepEnd or outcomeOriginal GeekMidst explanatory diagram, not an official Salesforce reference.

Select any step in the diagram, or use Step through, to see what happens at that point and why.

Text version: every step in order
  1. Client request ClientWeb, mobile or partner app

    The client sends a request with an access token and a correlation ID, so the call can be traced through every system it touches.

    Next: Gateway or middleware

  2. Gateway or middleware API gatewayAuth, rate limits

    A gateway or middleware layer such as MuleSoft gives clients one stable API, applies rate limits and shapes payloads, so clients are not tied to Salesforce internals.

    Next: Token valid?

  3. Token valid? API gateway

    Check the token, its scopes and the client identity before anything reaches Salesforce. Each client should have its own credentials so access can be revoked separately.

    Next: Yes: Salesforce API; No: Request rejected

  4. Request rejected ClientClear error code returned

    Return a clear 401 or 403 with no internal detail. Log the attempt; repeated failures from one client are worth an alert.

    End of the flow.

  5. Salesforce API SalesforceREST, Composite or Bulk

    Pick the API for the job: REST for single records, Composite to group related calls, Bulk for large volumes. The wrong choice shows up as API limit pressure.

    Next: Business logic

  6. Business logic SalesforceFlow or Apex rules

    Business rules run inside Salesforce with the integration user's permissions. Give that user only the objects and fields the integration needs.

    Next: Named credential

  7. Named credential SalesforceStored auth for callouts

    Outbound calls use a named credential and external credential, so endpoints and secrets are not written into code and can be rotated without a deployment.

    Next: System of record

  8. System of record System of recordERP, billing, core

    The system that owns the data applies the change or returns it. Agree which system is the master for each field to avoid two systems overwriting each other.

    Next: Response sent

  9. Response sent ClientResult plus correlation ID

    The client gets the result, or a clear error, along with the correlation ID for support. Keep response shapes stable when versions change.

    End of the flow.

A client calls an API gateway or middleware layer, which checks the token and forwards valid requests to Salesforce APIs. Flow or Apex logic runs, calls the system of record through a named credential, and the result is returned to the client. Original GeekMidst explanatory diagram; not an official Salesforce reference architecture.

Secrets in code or custom settings?

We can audit how your org stores integration credentials and move callouts to Named and External Credentials with a clear access model.

Request a security review →

Tell us what you are trying to fix.

Share your Salesforce setup, goals and constraints. A practitioner reads every message and replies with questions, first thoughts or an honest view of whether you need outside help at all.

Talk to a Salesforce Expert
Book a Consultation