Loading

Using External Credentials from Salesforce Named Credential in Apex

Data pubblicazione: Apr 2, 2026
Descrizione

To securely manage sensitive data such as API keys, one approach is to store the key using External Credentials and associate it with a Named Credential in Salesforce. Within the External Credential configuration, a Principal is defined to hold the API key securely.

In this below scenario, an attempt was made to reference the API key within an Apex class by injecting the secret into the endpoint URL:

String apiKey = '{!$Credential.GooglePlacesAPINew.api_key}';

String url = NAMED_CREDENTIAL_NEW + AUTOCOMPLETE_ENDPOINT +
             '?input=' + EncodingUtil.urlEncode(input, 'UTF-8') +
             '&types=address' +
             '&key=' + apiKey;

This resulted in the following error:

getting address predictions: Illegal character in opaque part at index 137: callout:GooglePlacesAPINewNamedCred/maps/api/place/autocomplete/json?input=10-25%2F141%2C+ri+s+Na+34143836&types=address&key={!HTMLENCODE($Credential.GooglePlacesAPINew.api_key)}

This Behaviours is WAD -

This behavior is working as designed. Salesforce does not allow encrypted (secret) values to be substituted into endpoint URLs when using Named Credentials. This limitation exists to prevent the potential exposure of sensitive data via URL parameters, which could be logged or cached in unintended ways.

 

 

Risoluzione

To resolve the error, you may consider one of the following approaches:

1.Use Named Credential Headers

Alternatively, pass the API key securely by configuring it as a custom header in your Named Credential. This allows the key to be transmitted securely without embedding it in the URL.

For more details, refer to: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm

2. Store the API Key in Custom Settings or Custom Metadata Types

Instead of using an encrypted secret in the URL, store the API key in a custom setting or custom metadata record. This allows you to retrieve the key dynamically in Apex without violating URL restrictions.

For implementation guidance, refer to: https://help.salesforce.com/s/articleView?id=ind.comms_create_and_add_your_google_maps_api_key.htm&type=5

 

Risorse aggiuntive

You can refer the  below article store the API key

https://help.salesforce.com/s/articleView?id=ind.comms_create_and_add_your_google_maps_api_key.htm&type=5

Numero articolo Knowledge

004695556

 
Caricamento
Salesforce Help | Article