Introduction
Named Credentials in Salesforce offer a secure and streamlined approach to handling authentication for outbound integrations. By specifying the URL of a callout endpoint and its required authentication parameters in one definition, named credentials help prevent sensitive credentials from being exposed within Apex code or to a developer who did not create the Named Credential record.
Key Takeaways
- Named Credentials provide a more secure alternative to hardcoding authentication details in Apex code.
- Centralize authentication management, simplifying updates and maintenance for integrations.
- Salesforce offers robust security features for Named Credentials, including encryption and fine-grained access control.
- Associating SSL Certificates to a Named Credential is a breeze.
Details
What: Named Credentials securely store authentication details for external systems, consisting of Named Credentials (endpoint URL) and External Credentials (authentication protocol and access permissions).
How: By linking a named credential to an external credential, developers can make callouts without exposing sensitive information directly in the code.
Why: Named Credentials are essential for enhancing security in outbound integrations by preventing hardcoded credentials, centralizing authentication management, enabling secure credential transmission, enforcing least privilege, and meeting compliance requirements.
When: Named Credentials are used whenever a Salesforce application needs to communicate with an external system that requires authentication.
Scenarios for Using Named Credentials
Named Credentials can be utilized in several specific callout scenarios within Salesforce:
- Apex Callouts: Developers can simplify and secure API calls to external systems from Apex code using Named Credentials. This method eliminates the need to hardcode sensitive authentication details like usernames, passwords, or API keys directly into the Apex code. Instead, developers can reference the Named Credential, which Salesforce uses to handle authentication automatically.
- External Data Sources: When setting up external data sources in Salesforce, Named Credentials can be used to store the connection and authentication details of the external system. This approach allows administrators to manage the credentials and connection information centrally without embedding them in various data source configurations.
- External Services: Salesforce External Services, used to integrate with external systems via REST API or SOAP API, can utilize Named Credentials. By referencing the Named Credential in the External Service configuration, the authentication process is streamlined and secured.
Best Practices
- Avoid hardcoding endpoints and credentials in Apex code.
- Utilize the principle of least privilege when configuring named credentials.
- Define named credentials with explicit, non-modifiable URIs to prevent unauthorized access.
Creating External and Named Credentials
- Create External Credentials:
- In Setup, go to “Named Credentials” -> “External Credentials” -> “New.”
- Provide a label and choose the “Authentication Protocol” based on the third-party app’s documentation.
- Select “OAuth 2.0”, “AWS Signature Version 4”, or “Custom” as needed.
- Configure Authentication Protocol Options:
- For OAuth 2.0: Choose “Browser Flow” or “JWT Bearer Flow” based on the API documentation. Select the configured “Authorization Provider” and save.
- For AWS Signature Version 4: Enter the “Service” and “Region” values as required and save.
- For Custom: No further configuration is needed at this stage, simply save the External Credential.
- Create Principal in External Credentials:
- After creating the External Credential, click “New” next to “Principals.”
- Provide a name and an optional sequence number.
- Choose “Named Principal” for org-wide login or “Per User Principal” for individual user logins.
- Save the Principal.
- Add External Principal Access to Permission Sets:
- In Setup, go to “Permission Sets” and choose the one you created earlier.
- Under “Apps,” click “External Credential Principal Access.”
- Click “Edit”, then move the desired Principal Access from “Available” to “Enabled External Principal Access.”
- Save the changes.
- Create Named Credentials:
- In Setup, navigate to “Named Credentials” -> “New.”
- Provide a label and enter the base URL of the third-party application.
- Enable “Enabled for Callouts.”
- Select the previously created External Credential.
- Choose the appropriate “Callout Options” as per the API documentation.
- Save the Named Credential.
Summary
- Use Named Credentials to enhance security in outbound integrations.
- Centralize and simplify authentication management.
- Ensure compliance with security standards.
- Prevent hardcoded credentials in Apex code.
- Enable fine-grained control over external service access.
Code Sample
Basic HTTP Callout using Named Credential
// Basic HTTP Callout using Named Credential
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyNamedCredential/some/path');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
System.debug(res.getBody());
POST Request using Named Credential
// POST Request using Named Credential
HttpRequest reqPost = new HttpRequest();
reqPost.setEndpoint('callout:MyNamedCredential/api/postData');
reqPost.setMethod('POST');
reqPost.setHeader('Content-Type', 'application/json');
reqPost.setBody('{"name":"John Doe"}');
HttpResponse resPost = new Http().send(reqPost);
System.debug(resPost.getBody());
Handling Query Parameters in the Request
// 3. Handling Query Parameters in the Request
HttpRequest reqWithParams = new HttpRequest();
reqWithParams.setEndpoint('callout:MyNamedCredential/resources?param1=value1¶m2=value2');
reqWithParams.setMethod('GET');
HttpResponse resWithParams = new Http().send(reqWithParams);
System.debug(resWithParams.getBody());
Using Named Credential for SOAP Web Service Callout
// Using Named Credential for SOAP Web Service Callout
HttpRequest reqSOAP = new HttpRequest();
reqSOAP.setEndpoint('callout:MyNamedCredential/soapService');
reqSOAP.setMethod('POST');
reqSOAP.setHeader('Content-Type', 'text/xml');
reqSOAP.setBody('<!-- SOAP request XML here -->');
HttpResponse resSOAP = new Http().send(reqSOAP);
System.debug(resSOAP.getBody());
Dynamic Endpoint in Named Credential Callout
// Dynamic Endpoint in Named Credential Callout
String dynamicResource = 'dynamicEndpoint';
HttpRequest reqDynamic = new HttpRequest();
reqDynamic.setEndpoint('callout:MyNamedCredential/' + dynamicResource);
reqDynamic.setMethod('GET');
HttpResponse resDynamic = new Http().send(reqDynamic);
System.debug(resDynamic.getBody());
Handling Response Status Codes
// Handling Response Status Codes
HttpRequest reqStatus = new HttpRequest();
reqStatus.setEndpoint('callout:MyNamedCredential/statusCheck');
reqStatus.setMethod('GET');
HttpResponse resStatus = new Http().send(reqStatus);
if(resStatus.getStatusCode() == 200) {
System.debug('Success: ' + resStatus.getBody());
} else {
System.debug('Error: ' + resStatus.getStatus());
}
Setting Custom Headers in Request
// Setting Custom Headers in Request
HttpRequest reqCustomHeader = new HttpRequest();
reqCustomHeader.setEndpoint('callout:MyNamedCredential/customHeader');
reqCustomHeader.setMethod('GET');
reqCustomHeader.setHeader('Custom-Header', 'HeaderValue');
HttpResponse resCustomHeader = new Http().send(reqCustomHeader);
System.debug(resCustomHeader.getBody());
Using Named Credential for PATCH Request
// Using Named Credential for PATCH Request
HttpRequest reqPatch = new HttpRequest();
reqPatch.setEndpoint('callout:MyNamedCredential/updateResource');
reqPatch.setMethod('PATCH');
reqPatch.setHeader('Content-Type', 'application/json');
reqPatch.setBody('{"property":"newValue"}');
HttpResponse resPatch = new Http().send(reqPatch);
System.debug(resPatch.getBody());
Making Callouts in Batch Apex using Named Credential
// Making Callouts in Batch Apex using Named Credential
global class MyBatchClass implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
// Query records to process
}
global void execute(Database.BatchableContext BC, List<sObject> records) {
HttpRequest reqBatch = new HttpRequest();
reqBatch.setEndpoint('callout:MyNamedCredential/batchProcess');
reqBatch.setMethod('POST');
// Process records and make callout
}
global void finish(Database.BatchableContext BC) {
// Post-processing actions
}
}
Using Named Credential in Scheduled Apex
// Using Named Credential in Scheduled Apex
global class MyScheduledClass implements Schedulable {
global void execute(SchedulableContext SC) {
HttpRequest reqSchedule = new HttpRequest();
reqSchedule.setEndpoint('callout:MyNamedCredential/scheduledTask');
reqSchedule.setMethod('GET');
HttpResponse resSchedule = new Http().send(reqSchedule);
System.debug(resSchedule.getBody());
}
}
Authorization header in callouts
// Handling authorization header in callouts with Named Credentials
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:MyNamedCredential');
request.setMethod('POST');
request.setHeader('Authorization', 'Bearer {!$Credential.AccessToken}');
HttpResponse response = new Http().send(request);
Authorization header with a session id
// Handling authorization header with a session id in Named Credentials
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Snowflake?token={!HTMLENCODE($Credential.SessionId)}');
request.setMethod('GET');
HttpResponse response = new Http().send(request);
References
- What are Named Credentials?^ https://help.salesforce.com/s/articleView?id=sf.nc_basics.htm&type=5
- Understand Legacy Named Credentials^ https://help.salesforce.com/s/articleView?id=sf.named_credentials_legacy_about.htm&type=5
- NamedCredential | Object Reference for the Salesforce Platform | Salesforce Developers^ https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_namedcredential.htm
- Named Credentials as Callout Endpoints | Apex Developer Guide | Salesforce Developers^ https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm
- NamedCredential | Tooling API | Salesforce Developers^ https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_namedcredential.htm
- Named Credentials^ https://help.salesforce.com/s/articleView?id=release-notes.rn_security_named_credentials.htm&release=246&type=5
- Named Credentials^ https://help.salesforce.com/s/articleView?id=sf.named_credentials_about.htm&type=5
- NamedCredentials Class | Apex Reference Guide | Salesforce Developers^ https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_ConnectAPI_NamedCredentials_static_methods.htm
- Create or Edit a Named Credential^ https://help.salesforce.com/s/articleView?id=sf.nc_create_edit_named_credential.htm&type=5
- Named Credentials Schema^ https://help.salesforce.com/s/articleView?id=sf.nc_parts_of_nc.htm&type=5
- Use Named Credential Formula Functions in Custom Headers^ https://help.salesforce.com/s/articleView?id=sf.nc_named_creds_formula_functions.htm&type=5
- Named Credential Callouts in Anonymous Blocks Require Customize Application Permission^ https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_anonymous_nc.htm&release=230&type=5
- Named Credential as Callouts for Salesforce Connect OData 2.0 or 4.0 Adapters^ https://help.salesforce.com/s/articleView?id=sf.platform_connect_external_data_source_example.htm&type=5
- Use Custom Headers for Basic Authentication with Named Credentials^ https://help.salesforce.com/s/articleView?id=sf.nc_custom_headers_basic_auth.htm&type=5
- Create a Named Credential for the Tooling API^ https://help.salesforce.com/s/articleView?id=sf.perm_uapa_create_a_named_credential.htm&type=5
- Authentication Protocols for Named Credentials^ https://help.salesforce.com/s/articleView?id=sf.nc_auth_protocols.htm&type=5
- Use API Keys in Custom Headers with Named Credentials^ https://help.salesforce.com/s/articleView?id=sf.nc_custom_headers_and_api_keys.htm&type=5
- Create Auth Providers and Named Credentials^ https://help.salesforce.com/s/articleView?id=sf.safety_cloud_auth_provider_creds.htm&type=5
Please share your ideas on this topic …