APEX-Q08Conceptual IntermediateApex & triggers#security#apex

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 sharing on classes (or inherited sharing for utilities). Use without sharing only for documented cases, isolated in small classes.
  • Object and field permissions: use user mode: WITH USER_MODE in SOQL, insert as user or Database.insert(records, AccessLevel.USER_MODE) for DML. Alternatively Security.stripInaccessible to 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: @AuraEnabled methods 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.