Skip to content
StackDecode
AdvancedLesson 33 of 37

Writing secure Apex

The code must enforce what the user is allowed to do.

Apex normally runs in system mode: it ignores the user's object and field permissions. You must enforce them.

apex
// user mode: enforces CRUD/FLS and sharing for the query
List<Account> accts = [SELECT Id, Name FROM Account WITH USER_MODE];

// or strip fields the user cannot read
SObjectAccessDecision d = Security.stripInaccessible(AccessType.READABLE, accts);
  • Use with sharing on classes.
  • Prevent SOQL injection: use bind variables (:value) or String.escapeSingleQuotes, never concatenate user input into queries.
  • Never hard-code credentials; avoid exposing sensitive data in debug logs.
  • Review with the Salesforce Code Analyzer (PMD-based).