Sub topic 1
Enforcing Object and Field Permissions in Apex with User Mode
Prerequisites
This chapter assumes you know basic Apex classes, SOQL, DML, profiles, permission sets, and unit tests. You should also know that CRUD means create, read, update, and delete permissions. FLS means field-level security.
Why Apex Ignores User Permissions by Default
Apex runs in system mode by default. System mode uses the permissions of the code, not the permissions of the user who started it. A query can therefore read fields that the user cannot see, and DML can change records the user cannot normally edit.
This behavior is useful for controlled backend operations, but it can expose data when Apex returns results to a user interface.
The with sharing keyword changes only record-level sharing behavior. It makes Apex respect sharing rules, organization-wide defaults, and manual sharing for records. It does not enforce object permissions or FLS.
public with sharing class AccountService {
public static List<Account> getAccounts() {
return [
SELECT Id, Name, Industry
FROM Account
WHERE Industry != null
WITH USER_MODE
LIMIT 50
];
}
}Sharing Is Not the Same as CRUD and FLS
These controls answer different questions:
| Control | Question it answers |
|---|---|
| Sharing | Can this user access this particular record? |
| CRUD | Can this user read or change this object? |
| FLS | Can this user read or change this field? |
A user might have read access to the Account object but lack access to the Industry field. Another user might have access to the field but not to a particular Account record.
What User Mode Enforces
User mode applies the running user's permissions to a database operation. For queries, WITH USER_MODE checks object permissions, FLS, and sharing. If the user lacks access to the object or a referenced field, the query can throw a QueryException.
User mode also applies to DML. The as user keyword and database methods that receive AccessLevel.USER_MODE enforce the user's permissions when records are inserted, updated, or deleted.
Exercise
What does with sharing enforce, and what does it leave unchecked?
Show answer
It enforces record-level sharing, but it does not enforce object permissions or field-level security.