Why are Named Credentials considered an essential security best practice for managing Apex HTTP callouts?
Answer
Basics: Hardcoding a URL and a password or token in Apex is a security and maintenance problem: secrets leak through source control, differ per sandbox, and expire. A Named Credential moves that to configuration. The code only references a name.
How it works:
- Create the credential (Setup > Named Credentials). In the current model, it is split: an External Credential (authentication protocol and principals) plus a Named Credential (URL) that points to it.
- Grant users access through a permission set mapped to the external credential principal.
- In Apex use
req.setEndpoint('callout:ERP_NC/orders'). - Salesforce resolves the base URL, adds authentication (for example OAuth bearer token, basic auth, AWS signature) and sends the request.
- For OAuth it obtains and refreshes the token automatically.
Advanced / deep dive: Benefits: no Remote Site Setting required for the host, secrets are encrypted and not visible to developers, environment-specific values differ per org without code change, and the same credential works from Apex, Flow HTTP Callout, External Services and Salesforce Connect. Authentication can be named principal (one identity for all) or per user (each user authenticates, preserving identity at the target). Custom headers and body formulas can use merge fields such as {!$Credential.Username} (legacy) or the external credential principal parameters (new model). Callouts count against the standard limits (100 per transaction, 120 seconds cumulative timeout), and callouts must still precede uncommitted DML in the transaction. Legacy-style Named Credentials still work but Salesforce directs new work to the External Credential model.
Code / config example: