Tag: apex-callouts

  • Keep Your Secrets Out of Sight: Salesforce Named Credentials Explained

    Hey folks, Abhi here!

    Quick question. If someone opened your org’s Apex classes today, would they find a client secret sitting in there?

    If you’re not 100% sure, this post is for you.

    Most Named Credentials tutorials stop at “write callout:My_API and you’re done”. And sure, that part is easy. But the question that matters more is a different one: where does the secret actually live, and who can read it?

    So let’s go a bit deeper than the usual tutorial. What each piece holds, what really happens when your code makes a call, how things change depending on who’s calling whom, where headers should go, and one sandbox trap that can send test calls to production. Grab a coffee.

    Why this matters, even if you don’t write code

    If you’re on the business side, here’s the short version.

    Your Salesforce org talks to other systems all the time: billing, marketing, finance, your website. To do that, it needs a kind of password for each one. If that password sits in the code, anyone who can see the code can use it, and a leak could expose customer data or let someone act inside those systems.

    Named Credentials keep those passwords locked away inside Salesforce, where only admins can set them and nobody can read them back. Less risk, cleaner audits, and one less thing to worry about when someone leaves the team.

    If you only read one section, make it this one. The rest is for the folks who build it.

    The problem with the “old way”

    You’ve probably seen this one. A client ID and secret pasted straight into an Apex class. Or tucked into a custom setting. Or a custom metadata record, because “at least it’s not in code”.

    Here’s the catch. All three end up in your metadata, which means they end up in Git, in every deployment package, and in front of anyone who can read the code or pull the metadata. And deleting the secret later doesn’t really help, because Git history remembers everything.

    Named Credentials solve this nicely. Your code just names a connection, and Salesforce takes care of the login.

    The four pieces (and which one holds the secret)

    There are four parts to the setup. The one thing I’d want you to remember: only the External Credential holds the secret, and that secret is typed into Setup. It never goes into a deployment.

    PieceWhat it holdsWhere the value comes from
    Named CredentialThe API’s URL, plus a link to the External CredentialMetadata, so you can deploy it
    External CredentialHow to log in (for example OAuth Client Credentials), the token URL, and under its Principal the client ID and secretURL in metadata; client ID and secret typed into Setup and stored encrypted
    External Client AppOnly needed when the API you’re calling is a Salesforce org. It issues the client ID and secret, allows the login flow and sets the Run As userCreated in the org you’re calling
    Permission setAccess to the External Credential PrincipalAssigned to whoever is allowed to make the call

    And this is all your Apex needs to know:

    HttpRequest req = new HttpRequest();
    req.setEndpoint('callout:My_API/services/data/v63.0/tooling/query/?q=' + EncodingUtil.urlEncode(soql, 'UTF-8'));
    req.setMethod('GET');
    HttpResponse res = new Http().send(req);

    No URL. No client ID. No secret. No token. Nice and clean.

    What actually happens when the code runs

    This part is really useful for debugging, so let’s walk through one call.

    Say a tool in your org queries its own Tooling API, and a user runs SELECT Id, ValidationName FROM ValidationRule LIMIT 5. Behind the scenes:

    1. Salesforce checks access first. Does the user have a permission set that gives access to the External Credential Principal? If not, the call stops right here.
    2. Your code builds the request using only the name: callout:My_API/services/data/v63.0/tooling/query/?q=...
    3. The Named Credential fills in the URL, something like https://<my-domain>.my.salesforce.com/services/data/v63.0/tooling/query/?q=...
    4. The External Credential gets a token. Salesforce sends the stored client ID and secret to the token URL with grant_type=client_credentials. All of this happens inside Salesforce. The user never sees any of it.
    5. The External Client App checks the login. The ID and secret match, Client Credentials Flow is switched on, so it hands back an access token for its Run As user.
    6. Salesforce attaches the token as Authorization: Bearer <token> and sends the request.
    7. The API answers, and here’s the bit people miss: the query runs as the Run As user, not as the person clicking the button.
    8. The user sees the rows.

    Once you know these steps, errors make a lot more sense. Call failing at step 4? The External Credential probably has no client ID and secret yet. Getting data from the wrong org? Check step 3. The Named Credential is probably still pointing at another org’s URL.

    One small clarification. The URL lives in the Named Credential, not in code, but it isn’t secret. Admins can see it and it’s part of the metadata. That’s fine, a URL on its own doesn’t give anyone access. If you’d still rather keep org URLs out of Git, commit a placeholder like YOUR_ORG_DOMAIN and set the real URL in each org.

    Who’s calling whom changes everything

    This is the part that makes it an architecture decision and not just a config task.

    The simple version: when Salesforce is the one making the call, your code never needs the secret. When someone else is calling Salesforce, they have to hold a credential. No way around that.

    DirectionSecret in code?Who holds the client ID and secret
    Salesforce calls a third-party APINoThe third party issues them, and an admin enters them in the External Credential in Setup
    Salesforce calls itself (same org)NoThe org’s own External Client App issues them, and an admin copies them into the same org’s External Credential
    Org A calls org BNoOrg B’s External Client App issues them, and an admin enters them in org A’s External Credential
    A third party calls SalesforceThe third party has to hold themYour External Client App issues them to the third party

    The org-to-org one deserves a second look. Yes, the client ID and secret still travel from one org to the other, but only through Setup. They never touch code, metadata or Git. And because every call into org B runs as org B’s Run As user, that user’s permissions decide what org A can see or change. So please don’t make that user a System Admin “just to get it working”.

    When a third party is calling into Salesforce, you can’t avoid handing over a credential. You can make it a lot safer though:

    • Go with the JWT Bearer flow if you can. The third party keeps a private key and you only upload its public certificate. There’s no shared secret at all.
    • Use an integration user with the least access it needs as the Run As user.
    • Lock down IP ranges, and rotate the secret when people leave.

    Where should headers go?

    This one confuses a lot of people, because both the External Credential and the Named Credential have a Custom Headers section. The difference is simply which calls get the header.

    A header on the External Credential goes out with every call, through every Named Credential linked to it. A header on the Named Credential only goes with calls through that one Named Credential.

    So here’s how I’d split it:

    • Secrets (client secret, API key, subscription key) get saved under the External Credential Principal, encrypted.
    • The header that carries a secret goes on the External Credential and points to it with a formula: {!$Credential.<ExternalCredential>.<Parameter>}. Salesforce swaps in the real value at send time.
    • A header that isn’t secret but differs per endpoint goes on that endpoint’s Named Credential.
    • The OAuth token needs nothing from you. Tick Generate Authorization Header and Salesforce adds Authorization: Bearer <token> by itself.

    Named Credential headers are optional, but they’re handy. An admin can change them in Setup without a deployment, each org can have its own value, and Flow and External Services pick them up too.

    A quick example. Say you’re calling an API that wants both an OAuth token and an API key:

    WhereSettingValue
    External Credential Partner_ExtCredProtocolOAuth 2.0 Client Credentials
    Token URLhttps://auth.example.com/oauth2/token
    PrincipalClient ID and secret from the provider; parameter ApiKey = the API key
    Custom HeaderX-API-Key = {!$Credential.Partner_ExtCred.ApiKey}
    Named Credential Partner_OrdersURLhttps://api.example.com/orders
    Custom Headerapi-version = 2024-01-01

    What Salesforce actually sends:

    GET https://api.example.com/orders/12345
    Authorization: Bearer eyJ0eXAi...
    X-API-Key: 3f9a...
    api-version: 2024-01-01

    The first two headers come from the External Credential, the last one from the Named Credential. The token is basically a temporary pass. Salesforce gets it from the provider using the client ID and secret, and renews it on its own when it expires.

    The sandbox trap

    Okay, this is the one that really bites.

    After a sandbox is created or refreshed from production, the Named Credential can come back still pointing at the production URL, and without a working secret. The External Client App might not come over at all. Best case, your callouts just fail. Worst case, a test in the sandbox quietly hits production.

    So after every sandbox creation or refresh, run through this:

    1. Check the External Client App exists. If it’s missing, deploy it.
    2. Change the Named Credential URL to the sandbox’s own My Domain URL, for example https://<my-domain>--<sandbox>.sandbox.my.salesforce.com.
    3. Set the External Credential token URL to the same domain plus /services/oauth2/token.
    4. In the External Client App, enable OAuth, add the api scope, switch on Client Credentials Flow and set the Run As user.
    5. Copy the sandbox’s own client ID and secret into the External Credential Principal.
    6. Make one test call and check that rows come back.

    Steps 1 to 3 can go in as metadata. Steps 4 and 5 have to be done in Setup, because the secret should never be part of a deployment. My suggestion: put this list in your refresh runbook so nobody has to remember it.

    Wrapping up

    Writing callout:<Named Credential> is the easy bit. The real thinking is in where each secret lives, who issues it, which user the call runs as, and how every environment gets its own credentials.

    Get those right, and your code, metadata and Git history stay clean, and a sandbox refresh never turns into a production incident.

    Now I’m curious. How does your team handle credentials across sandboxes? A separate secret per environment, or one shared across all of them? Tell me in the comments.

    Until next time, folks!