How do you enforce security in Apex?
Your confidence:Not rated
Model answer
Apex runs in system mode by default, so security is a design responsibility.
- Record sharing: declare
with sharingon classes (orinherited sharingfor utilities). Usewithout sharingonly for documented cases, isolated in small classes. - Object and field permissions: use user mode:
WITH USER_MODEin SOQL,insert as userorDatabase.insert(records, AccessLevel.USER_MODE)for DML. AlternativelySecurity.stripInaccessibleto remove fields the user can't read or edit. - Dynamic SOQL: bind variables (
Database.queryWithBinds), and whitelist field names against the schema. No string concatenation of user input (SOQL injection). - Entry points:
@AuraEnabledmethods validate inputs and never trust IDs from the client; REST resources are exposed only to authenticated integration users with least privilege. - Secrets: Named Credentials and External Credentials, never secrets in code or custom settings visible to users.
- Output: encode output in Visualforce or custom HTML to prevent XSS; LWC escapes by default.
- Review: static analysis (PMD, Salesforce Code Analyzer) in CI.
โ Key points to hit
โ Red-flag answers
- 'with sharing enforces field-level security'
- Concatenating user input into SOQL
- Secrets in custom settings or code
โช Follow-ups
When is `without sharing` justified?
For a narrow, documented operation that must see records the user can't, such as checking for duplicates across the org or writing an audit record. Keep it in a small class, expose only the minimum result, and review it.
What does `inherited sharing` do when the class is the entry point?
It runs as with sharing. When called from another class, it takes the caller's sharing mode. That makes it a safe default for utility classes.