Advanced 30 min read

Secure Apex Controllers

By the end of this lesson, you'll be able to:

  • Apply this module's security layers together in one realistic controller method
  • Explain why a controller exposed to the UI needs extra scrutiny
  • Recognize the layered-defense pattern across sharing, CRUD/FLS, user mode, and injection safety

Prerequisites: "SOQL Injection"

Why controllers deserve extra scrutiny

A method exposed to a UI (a later Lightning Web Components module covers the @AuraEnabled mechanics) can be called by any authenticated user directly, with whatever arguments they choose — unlike an internal helper method only ever called by trusted code elsewhere in the org. This makes controller methods a natural place where every layer from this module actually matters at once.

A secure controller method, layer by layer

public with sharing class AccountSearchController {
    public static List<Account> searchAccountsByName(String searchTerm) {
        // Layer 1: "with sharing" — only records this user can see
        // Layer 2: bind variable — no SOQL injection risk
        // Layer 3: WITH USER_MODE — enforces CRUD/FLS automatically
        return [
            SELECT Id, Name, Industry
            FROM Account
            WHERE Name LIKE :('%' + searchTerm + '%')
            WITH USER_MODE
        ];
    }
}

Four lessons' worth of this module, applied together in one small, realistic method: with sharing (record-level access), a bind variable (injection-safe), and WITH USER_MODE (automatic CRUD/FLS) — none of these alone would be a complete defense; together, they are.

The layered-defense mindset

No single technique from this module is "the" security fix — sharing, CRUD/FLS, and injection safety each address a genuinely different risk, and a method can fail on any one of them independently even while doing the others correctly. The habit this closing lesson leaves you with: when writing any method a UI or external caller can invoke, run through all four layers deliberately, rather than assuming one check covers everything.

Exercise

Write a secure controller method getContactsByLastName(String lastName) applying all three layers: with sharing on the class, a bind variable, and WITH USER_MODE.

Show hint

Combine the class declaration, bind variable, and WITH USER_MODE from this lesson.

APEX

Secure Apex Controllers Quiz

1. Why does no single technique from this module count as "the" complete security fix?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

This closing lesson combines every security concept from this module into one realistic, UI-facing controller method — the place where all of these defenses matter together most directly.