Hardcoding API Credentials Instead of Using Named Credentials
“Hardcoded API keys in Apex are a security audit's worst nightmare.”
What Happened
Early in my Cloud Nimbus consulting days, I stored an API key directly in an Apex class for a payment integration. The client's security team found it during a code review. They could see the key in version history, in every sandbox, and in every deployment package. I had to rotate the key, scrub the history, and explain to a very unhappy CISO why their payment credentials were in plain text.
The Wrong Way
public class PaymentService {
private static final String API_KEY = 'sk_live_4eC39HqLyjWDarjtT1zdp7dc';
private static final String ENDPOINT = 'https://api.stripe.com/v1/charges';
public static HttpResponse charge(Decimal amount) {
HttpRequest req = new HttpRequest();
req.setEndpoint(ENDPOINT);
req.setHeader('Authorization', 'Bearer ' + API_KEY);
req.setMethod('POST');
req.setBody('amount=' + (amount * 100).intValue());
return new Http().send(req);
}
}The Right Way
// Setup > Named Credentials > "StripeAPI"
// URL: https://api.stripe.com
// Auth: Per User or Named Principal with OAuth or Custom Header
// External Credential stores the Bearer token securely
public class PaymentService {
public static HttpResponse charge(Decimal amount) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:StripeAPI/v1/charges');
req.setMethod('POST');
req.setBody('amount=' + (amount * 100).intValue());
// Auth header injected automatically by Named Credential
return new Http().send(req);
}
}The Lesson
Named Credentials exist for a reason. They handle auth, endpoint management, and per-environment config. Never put secrets in code.
Enjoyed this? Get more like it.
Glen's Musings — AI, investing, and building things. Occasional. Free.
More Integration Mistakes
Making a Callout from a Trigger
You cannot make HTTP callouts from a synchronous trigger context. Period.
Read moreAnnoyingNo Retry Logic on External API Calls
External APIs fail. Your integration should expect that.
Read morePainfulPublishing Platform Events Without Error Handling
Platform Events can fail to publish. If you don't check, you'll never know.
Read more