callout: protocol in Apex, you automatically eliminate hardcoded credentials and bypass explicit Remote Site Settings.
Named Credentials are a powerful feature in Salesforce that allow you to securely authenticate and connect to external services and APIs without exposing sensitive information like usernames and passwords. In this blog post, we'll delve into the world of Named Credentials, understand their significance, and provide you with in-depth code examples to illustrate their implementation in various scenarios.
1. What are Named Credentials?
Named Credentials specify the URL of a callout endpoint and its required authentication parameters in a single, declarative definition in Salesforce. They act as a central hub for securely storing authentication details such as usernames, passwords, OAuth tokens, and certificates, eliminating the need to hardcode authorization headers or manage Remote Site Settings manually.
2. Advantages of Using Named Credentials
- Enhanced Security: Shields sensitive secrets, passwords, and OAuth tokens completely from Apex source code.
- No Remote Site Settings Required: Callouts invoking the
callout:schema automatically bypass explicit Remote Site Whitelisting. - Centralized Environment Management: Easily update endpoint URLs and credentials declaratively across sandbox deployment stages without modifying Apex classes.
- Encrypted Storage: All underlying secrets, passwords, and authentication tokens are encrypted at rest by Salesforce.
3. Creating Named Credentials in Salesforce
- Navigate to Setup > Named Credentials.
- Click New Named Credential (or configure modern External Credentials paired with a Named Credential).
- Enter the Label, Name, and base URL of the target external service.
- Select the appropriate Authentication Protocol (e.g., Password Authentication, OAuth 2.0, AWS Signature Version 4, or Client Certificate).
- Save and complete the authentication handshake flow for the endpoint.
4. Code Examples
HttpRequest req = new HttpRequest();
// Use the 'callout:' schema followed by the Named Credential API Name
req.setEndpoint('callout:My_Named_Credential/services/data/v58.0/query?q=SELECT+Id+FROM+Account');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody());
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Named_Credential/restApiEndpoint');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody('{"key": "value"}');
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody());
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Salesforce_Org_NC/services/apexrest/MyRestService');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody());
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Named_Credential/oauth2/token');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
// Use merge fields like {!$Credential.UserName} and {!$Credential.Password} if using Per-User or Principal Credentials
req.setBody('grant_type=password&client_id=myClientId&client_secret=myClientSecret&username={!$Credential.UserName}&password={!$Credential.Password}');
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody());
callout: followed by the Exact Named Credential API Name (e.g., req.setEndpoint('callout:My_NC_Name/path')). Omitting callout: or including a protocol like https:// inside the code will cause the callout to fail or bypass the stored authentication credentials entirely!
- Rule: Use modern External Credentials for authentication protocol settings and pair them with Named Credentials for target URL endpoints.
- Gain: Zero hardcoded API keys/passwords in Apex, automatic Remote Site whitelisting, and secure encrypted credential storage.
- Price: Setup requires administrative configuration in Setup and Permission Set access assignment for External Credentials.
- Limits: Custom authorization headers that do not use standard OAuth/Basic auth schemas may require merge field injection (
{!$Credential.Password}).
5. Best Practices
- Never Hardcode Secrets: Always store Client Secrets, Passwords, and Tokens in Named Credentials or External Credentials.
- Use Dynamic Merge Fields: Utilize
{!$Credential.UserName}and{!$Credential.Password}where applicable for custom headers or request bodies. - Apply Principle of Least Privilege: Restrict Named Credential and External Credential access using Permission Sets and User Profiles.
6. Conclusion
Named Credentials are an essential architecture tool for securing REST and SOAP integrations in Salesforce. By abstracting authentication out of Apex code and into declarative configurations, you improve maintainability across environments and uphold robust enterprise security standards.