Concept 6 of 8Secure development

Secure code: Apex, LWC and integrations

The OWASP-style risks on Salesforce: data access without FLS or sharing, SOQL injection, XSS, insecure guest-accessible methods, secrets in code, CSP and Lightning Web Security, and tooling to catch them.

Your confidence:Not rated

Simple explanation

RiskOn SalesforcePrevention
Broken access controlApex runs in system mode; @AuraEnabled methods trust client-supplied IDswith sharing, user-mode queries and DML, check access to the IDs passed in
InjectionDynamic SOQL/SOSL built from stringsBind variables, Database.queryWithBinds, whitelist field names
Cross-site scripting (XSS)Visualforce or custom HTML rendering user input; lwc:dom="manual" and innerHTMLLWC templates escape by default; encode output in Visualforce (JSENCODE, HTMLENCODE); avoid raw HTML
Sensitive data exposureSecrets in code, custom settings or debug logsNamed/External Credentials, protected custom metadata, no secrets in logs
Insecure guest accessGuest-accessible Apex with without sharingMinimise guest classes; validate every input; return minimal data
Third-party scriptsExternal JS in componentsLightning Web Security isolation, CSP Trusted Sites only as needed

Tooling: Salesforce Code Analyzer (PMD, ESLint and security rules) in CI, peer review checklists, and the security review for AppExchange packages.

Real-world analogy

Secure code is a restaurant kitchen's food-safety rules. The food is fine at delivery (the platform is secure), but a careless cook can still contaminate dishes: raw ingredients mixed with ready meals (injection), unlabelled allergens (exposed data), or the back door left open to the street (guest-accessible code).

Worked example

An @AuraEnabled method that safely returns a contact's cases for the logged-in user:

public with sharing class CaseListController {
    @AuraEnabled(cacheable=true)
    public static List<Case> openCasesFor(Id contactId) {
        // The user must be able to see the contact; user mode enforces sharing, CRUD and FLS.
        List<Contact> visible = [SELECT Id FROM Contact WHERE Id = :contactId WITH USER_MODE LIMIT 1];
        if (visible.isEmpty()) {
            throw new AuraHandledException('Contact not found.');
        }
        return [
            SELECT Id, CaseNumber, Subject, Status, CreatedDate
            FROM Case
            WHERE ContactId = :contactId AND IsClosed = false
            WITH USER_MODE
            ORDER BY CreatedDate DESC
            LIMIT 50
        ];
    }
}

Diagram

Rendering diagram…

Key points

  • Treat every @AuraEnabled, REST and guest-accessible method as an API exposed to attackers.
  • User mode + with sharing; verify access to IDs passed in.
  • Bind variables against injection; escape output against XSS.
  • Secrets in Named/External Credentials, never in code or logs.
  • Lightning Web Security and minimal CSP Trusted Sites.
  • Code Analyzer in CI and review checklists.

Limits and gotchas

  • cacheable=true methods may return cached data; never use them for data that must reflect permission changes instantly or for DML.
  • AuraHandledException messages reach the user; don't leak internal details.
  • Debug logs can capture sensitive values; limit who can enable them in production.
  • Managed packages with without sharing code run in your org; include them in security reviews.

🎀 How to say this in an interview

Show you treat controller methods as public APIs: access checks, user mode, binds, minimal returns. Mention automated scanning in CI and guest-accessible code as the highest risk.

Common follow-ups

Why check access to the contact ID if the case query already runs in user mode?

User mode on the case query only returns cases the user can see, but checking the contact first gives a clear error and prevents probing for IDs. It's defence in depth, and it matters when the method does more than read.

How do you stop secrets leaking in logs?

Never log tokens or personal data, restrict who can enable debug logs, and use Named Credentials so code never holds secrets.