Skip to main content

Code reviews rule: Hardcoded callouts authentication

Written by David Martin
Updated yesterday

Hardcoded callouts authentication

Why is this an issue?

Hardcoding endpoint URLs and authentication credentials in Apex code creates several problems:

  • Security risk: Credentials in code can be exposed through version control or logs.

  • Maintenance burden: Changing endpoints requires code changes and deployments.

  • Environment issues: Different environments (sandbox vs. production) often need different endpoints.

  • No credential rotation: Updating passwords requires code changes.

Named Credentials solve these problems by storing endpoint URLs and authentication details securely in Salesforce configuration.

Examples

Example of incorrect code:

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/data');
request.setHeader('Authorization', 'Bearer ' + apiKey);
request.setMethod('GET');
HttpResponse response = http.send(request);

Example of correct code:

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Example_API/data');
request.setMethod('GET');
// Authentication is handled automatically by the Named Credential
HttpResponse response = http.send(request);

How can I fix violations?

  1. Create a Named Credential: In Setup, navigate to Named Credentials and create a new credential with the endpoint URL and authentication details.

  2. Update code: Replace hardcoded URLs with callout:NamedCredentialName/path.

  3. Remove credential handling: Let the Named Credential handle authentication headers.

When should I disable this rule?

You may dismiss specific violations for:

  • Public APIs that require no authentication

  • Integration tests using mock endpoints

Resources

Did this answer your question?