Now inviting automation leaders: publish your playbook as a skill, under your own name. Publish yours →
Automation Skills
All skills/Sf integration/Security-best-practices
Reference · Sf integration

Security-best-practices

Part of Sf integration. Install the skill and your agent reads this page when it needs the depth.

<!-- Parent: sf-integration/SKILL.md -->

Integration Security Best Practices

Overview

Security is critical for integrations. This guide covers best practices for securing Salesforce integrations with external systems.

Credential Management

DO: Use Named Credentials

// ✅ CORRECT - Named Credential handles auth
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MySecureAPI/resource');

DON'T: Hardcode Credentials

// ❌ WRONG - Never hardcode credentials
req.setHeader('Authorization', 'Bearer sk_live_abc123...');
req.setEndpoint('https://api.example.com');

Credential Storage Rules

Item Storage Location Never Store In
API Keys Named Credential Apex code, Custom Settings
Client Secrets Named Credential / External Credential Source control
Certificates Certificate & Key Management Static Resources
Passwords Named Credential Custom Metadata

OAuth Best Practices

Scope Minimization

Request only necessary scopes:

✅ read:orders write:orders
❌ admin:* read:* write:*

Token Handling

PKCE for Public Clients

For mobile or SPA clients:

Use Authorization Code with PKCE, not Implicit flow

Network Security

Remote Site Settings

Certificate Validation

IP Restrictions

For Connected Apps:

Input Validation

Validate External Data

// Validate before processing
public static void processExternalData(String externalId) {
    // Validate format
    if (!Pattern.matches('[A-Za-z0-9]{10,20}', externalId)) {
        throw new ValidationException('Invalid external ID format');
    }

    // Sanitize for SOQL
    String safeId = String.escapeSingleQuotes(externalId);
}

Output Encoding

// Encode data sent to external systems
String encodedData = EncodingUtil.urlEncode(userData, 'UTF-8');

Error Handling Security

Don't Expose Internal Details

// ❌ WRONG - Exposes internal structure
throw new CalloutException('Failed: ' + response.getBody());

// ✅ CORRECT - User-friendly, log details separately
System.debug(LoggingLevel.ERROR, 'API Error: ' + response.getBody());
throw new CalloutException('Unable to complete request. Contact support.');

Log Securely

// ❌ WRONG - Logs sensitive data
System.debug('Request: ' + JSON.serialize(request)); // May contain PII

// ✅ CORRECT - Redact sensitive fields
System.debug('Request to: ' + endpoint + ', Status: ' + statusCode);

API Security Patterns

Rate Limiting Awareness

if (response.getStatusCode() == 429) {
    String retryAfter = response.getHeader('Retry-After');
    // Implement backoff, don't hammer the API
}

Idempotency Keys

For POST requests that shouldn't duplicate:

req.setHeader('Idempotency-Key', generateUniqueKey());

Request Signing

For APIs requiring signature:

String signature = generateHmacSignature(payload, secretKey);
req.setHeader('X-Signature', signature);

User Context Security

Per-User vs Named Principal

Scenario Use
User-specific data access Per-User Principal
Background/batch jobs Named Principal
Service integrations Named Principal
User-initiated with audit Per-User Principal

Audit Logging

public static void logIntegrationActivity(String operation, Id userId, String externalSystem) {
    Integration_Log__c log = new Integration_Log__c(
        Operation__c = operation,
        User__c = userId,
        External_System__c = externalSystem,
        Timestamp__c = Datetime.now()
    );
    insert log;
}

Platform Event Security

Sensitive Data in Events

Event Consumer Validation

trigger SecureEventHandler on My_Event__e (after insert) {
    for (My_Event__e event : Trigger.new) {
        // Validate event source/origin if possible
        if (!isValidEventSource(event)) {
            System.debug(LoggingLevel.WARN, 'Suspicious event: ' + event.ReplayId);
            continue;
        }
        processEvent(event);
    }
}

Security Checklist

Before Deployment

Regular Review

Compliance Considerations

GDPR / Data Privacy

SOC 2 / Security Audits

HIPAA (Healthcare)

Publish your skill

Copy this prompt into Claude Code, Codex or any agent. It walks you through your first skill in about 20 minutes, with you as the author.

Click to copy.