Using Named Credentials to make Salesforce Apex more secure

Named Credentials in Salesforce serve as a secure method of managing authentication data for external services. They encapsulate the endpoint URL and the required authentication credentials (username, password, OAuth, etc.), providing a simplified and secure way to call out to external APIs from Salesforce.

When developing on the Salesforce platform, security is a paramount concern, especially when dealing with external services or data sources. Apex code, allows developers to execute complex business logic on the Salesforce platform. However, when interacting with external systems, the handling of credentials and sensitive data can significantly impact the security of the application. The use of named credentials is a best practice in this context, and its absence can make Apex code less secure for several reasons:

  1. Hardcoded Credentials: Without named credentials, developers might resort to hardcoding credentials (like usernames, passwords, or API keys) directly into the Apex code. This practice is highly insecure because:
    • The credentials are stored in plain text, making them easily accessible to anyone who can view the code.
    • It increases the risk of accidental exposure, for example, through code sharing or version control systems.
    • Managing and rotating credentials becomes cumbersome, often leading to outdated or compromised credentials being left in place for extended periods.
  2. Lack of Centralized Management: Named credentials provide a centralized way to manage and rotate credentials without altering the Apex code. Without named credentials, each integration point might handle credentials differently, complicating credential management, rotation, and security auditing. This decentralized approach increases the risk of security lapses and makes it harder to enforce consistent security policies.
  3. Insecure Credential Transmission: Named credentials support secure methods for transmitting credentials to external services, such as OAuth authentication mechanisms, which do not require exposing the credentials directly. Without using named credentials, developers might implement less secure methods of transmission, such as basic authentication over unencrypted connections, which can be intercepted by attackers.
  4. Limited Scope and Fine-grained Control: Named credentials allow for the specification of the scope and the precise control of what the external service can access. This principle of least privilege reduces the potential damage if those credentials were ever compromised. Without using named credentials, Apex code might provide broader access than necessary, increasing the risk if those credentials are misused.
  5. Compliance and Auditing Issues: For many organizations, especially those in regulated industries, maintaining compliance with standards such as GDPR, HIPAA, or PCI DSS is critical. Named credentials help in meeting such compliance requirements by providing a secure and auditable way of handling external authentication. Without named credentials, organizations may find it challenging to prove that they are managing external credentials securely, leading to compliance risks.
  6. Security Features and Enhancements: Salesforce continuously updates and enhances security features related to named credentials, such as encrypted storage and automatic session handling. By not using named credentials, developers miss out on these security enhancements, which are designed to protect against evolving threats.

Avoiding the use of named credentials in Apex code leads to less secure applications due to the risks associated with hardcoded credentials, lack of centralized management, insecure transmission methods, broader than necessary access scopes, compliance challenges, and missing out on Salesforce’s security enhancements. Adopting named credentials is a best practice that significantly contributes to the overall security posture of Salesforce applications.


OK you are sold ( hopefully 🙂 ) so now let’s see how we can create a named credential:


1. Creating a Named Credential

To create a Named Credential in Salesforce, follow these steps:

  1. Navigate to Setup: Log in to your Salesforce org, click on the gear icon in the top right corner, and select ‘Setup’.
  2. Open Named Credentials: In the Quick Find box, type “Named Credentials” and select it under the ‘Security’ section.
  3. New Named Credential: Click the ‘New Named Credential’ button.
  4. Configure the Named Credential:
    • Label and Name: Provide a label and a unique name for the Named Credential.
    • URL: Enter the endpoint URL of the external service you want to connect to.
    • Identity Type: Choose “Named Principal” for a single set of credentials shared across the org, or “Per User” if each user will use their own credentials.
    • Authentication Protocol: Select the appropriate authentication method (Password Authentication, OAuth 2.0, JWT, etc.). The fields displayed will change based on the selected protocol.
    • Authentication Settings: Fill in the required fields based on your selected authentication protocol. For OAuth, you may need to specify the scope, authorization and token endpoint URLs, consumer key, and consumer secret.
    • Scope (if applicable): Enter the scope of the access request if required by the external service.
  5. Save: Click ‘Save’ to create the Named Credential.

2. Using Named Credentials in Apex

Once you’ve set up a Named Credential, you can use it in Apex to call out to external services without hardcoding URLs or authentication details. Here’s how to make a callout using a Named Credential:

HttpRequest req = new HttpRequest();

// Optional: Set request headers or body
req.setHeader('Content-Type', 'application/json');

// Send the request
Http http = new Http();
HTTPResponse res = http.send(req);

// Process the response


In the setEndpoint method, callout:MyNamedCredential is a placeholder for the Named Credential you created. Salesforce automatically handles the authentication based on the configuration of the Named Credential.

Had we chosen to not use a named credential, our code would have looked like:

HttpRequest req = new HttpRequest();
// Manually specify the endpoint URL
req.setHeader('Content-Type', 'application/json');

// Manually handle authentication
String username = 'myUsername';
String password = 'myPassword';
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);

Http http = new Http();
HTTPResponse res = http.send(req);


The version without Named Credentials is more verbose, requiring manual specification of the endpoint URL and handling of the authentication details within the Apex code. This increases complexity and the potential for errors or security issues.


3. Best Practices and Considerations

  • Least Privilege: Configure the Named Credential with the minimum necessary permissions on the external service.
  • Monitoring and Logging: Utilize Salesforce’s monitoring tools to track the usage and performance of your callouts.
  • Security: Regularly review and update the credentials and permissions associated with your Named Credentials, especially when using OAuth tokens that may expire or when changing passwords.
  • Error Handling: Implement robust error handling in your Apex code to gracefully handle failed callouts or unexpected responses from the external service.

4. Advanced Features

  • Merge Fields: Salesforce allows the use of merge fields in the endpoint URL of a Named Credential, enabling dynamic URL construction based on record data.
  • Refresh Tokens: For OAuth configurations, ensure that the Named Credential is set up to handle refresh tokens if the service supports them. This keeps the session active without manual intervention.

Named Credentials are a powerful feature in Salesforce for securely integrating with external services. By centralizing the management of endpoint URLs and authentication details, they simplify the development of secure, maintainable, and scalable integrations. Following the steps outlined in this tutorial, you can effectively utilize Named Credentials in your Salesforce org to enhance the security and efficiency of your external service integrations.



Leave a Comment