Sub topic 11
Enforcing FLS with WITH USER_MODE and AccessLevel.USER_MODE
This chapter assumes you know basic Apex and SOQL. It also assumes you know that Apex runs in system mode by default, so it ignores the running user's field-level security (FLS). User mode is the simplest way to change that.
What user mode does
User mode runs a query or DML operation with the current user's object permissions, FLS, and sharing rules. System mode ignores all three. User mode is a per-operation setting. The rest of your class keeps its normal behavior.
If the user lacks access, Apex throws an exception. It does not silently skip the field. This is the main difference from Security.stripInaccessible, which the next chapter covers.
User-mode SOQL
Add WITH USER_MODE to a static query:
List<Account> accounts = [
SELECT Id, Name, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
WITH USER_MODE
];If the user cannot read AnnualRevenue, the query throws a QueryException. Fields used in WHERE and ORDER BY are checked too, so a user cannot filter on a field they cannot see.
For dynamic SOQL, pass an access level to Database.query:
String soql = 'SELECT Id, Name FROM Account WHERE Industry = :industry';
String industry = 'Technology';
List<Account> accounts = Database.query(soql, AccessLevel.USER_MODE);User-mode DML
Pass AccessLevel.USER_MODE to a Database method:
Account acc = new Account(Name = 'Acme', AnnualRevenue = 1000000);
Database.insert(acc, AccessLevel.USER_MODE);The operation checks create or edit permission on the object and on every field you set. If the user cannot edit AnnualRevenue, the insert throws a DmlException. The same overloads exist for update, upsert, delete, and their bulk forms.
Choosing where to apply it
| Approach | Behavior when access is missing |
|---|---|
| Default (system mode) | No check, runs anyway |
| `WITH USER_MODE` or `AccessLevel.USER_MODE` | Throws an exception |
Common errors
- Catching the exception too broadly. Catch
QueryExceptionorDmlExceptionand return a clear message. Do not swallow it. - Expecting
WITH USER_MODEto apply to a whole class. It applies to one statement. - Forgetting that sharing is also enforced. A user-mode query returns only records the user can see, even if the class is declared
without sharing. - Using the older
WITH SECURITY_ENFORCED. It checks only fields in theSELECTclause and has no DML equivalent. PreferWITH USER_MODE.
Exercise
A user's profile cannot read Account.Internal_Notes__c. What happens when this user runs [SELECT Id, Internal_Notes__c FROM Account WITH USER_MODE], and what happens without WITH USER_MODE?
Show answer
With WITH USER_MODE, Apex throws a QueryException because the user cannot read the field. Without it, the query runs in system mode and returns the field value, ignoring the user's FLS.