Sub topic 11
Enforcing permissions with user-mode queries and DML
Earlier chapters showed that with sharing limits which records a class can see, and that it does nothing for object permissions or field-level security (FLS). This chapter covers the Apex feature that closes that gap. It assumes you can read Apex and SOQL, you know how profiles and permission sets grant object and field access, and you know how a with sharing class behaves.
What user mode changes
Apex normally runs in system mode. Object permissions and FLS are ignored, and record-level sharing is applied only if the class declares it. User mode is a per-operation setting that makes a single query or DML statement run with the running user's access. It enforces three things:
- Object permissions (create, read, edit, delete).
- Field-level security on every field the operation touches.
- Sharing rules, organization-wide defaults, and the rest of record-level access.
The third point is easy to miss. A user-mode operation applies record-level sharing even when the surrounding class is declared without sharing. The operation's access level takes precedence for that one statement. The rest of the method still runs in system mode.
| Mechanism | Record sharing | Object permissions | Field-level security |
|---|---|---|---|
| `with sharing` alone | Yes | No | No |
| `without sharing` alone | No | No | No |
| `WITH USER_MODE` / `AccessLevel.USER_MODE` | Yes | Yes | Yes |
User-mode SOQL
Add WITH USER_MODE to a static query. The example below uses a with sharing class, so the keyword and the clause work together.
public with sharing class ContactReader {
public static List<Contact> findByLastName(String lastName) {
return [
SELECT Id, LastName, Email
FROM Contact
WHERE LastName = :lastName
WITH USER_MODE
];
}
}If the user cannot read Contact.Email, the query throws a System.QueryException. It does not return null for that field. The check covers fields in the SELECT list and also fields used in WHERE and ORDER BY. This is stricter than the older WITH SECURITY_ENFORCED clause, which checks only the SELECT fields. For new code, prefer WITH USER_MODE.
Dynamic SOQL takes an access level as an argument. Prefer Database.queryWithBinds, because it keeps values out of the query string and so avoids SOQL injection.
public with sharing class DynamicAccountReader {
public static List<Account> findByName(String accountName) {
Map<String, Object> binds = new Map<String, Object>{
'accountName' => accountName
};
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Name = :accountName',
binds,
AccessLevel.USER_MODE
);
}
}Database.query(queryString, AccessLevel.USER_MODE) also exists. It reads variables from the local scope, so the binding is implicit. Use queryWithBinds when you build the query from several inputs.
User-mode DML
There are two ways to run DML in user mode. The first is the as user keyword on a DML statement:
public with sharing class ContactWriter {
public static void createContact(String lastName) {
Contact c = new Contact(LastName = lastName);
insert as user c;
}
}The second is a Database method that takes an AccessLevel:
public with sharing class ContactUpdater {
public static List<Database.SaveResult> updateContacts(List<Contact> contacts) {
// allOrNone = false: failed records are reported in the results
return Database.update(contacts, false, AccessLevel.USER_MODE);
}
}Use the Database form when you need partial success or per-record error handling. The as user form is shorter and fits cases where one failure should abort the transaction.
DML in user mode checks the object's create, edit, or delete permission. It also checks edit or create access on every field you set. A record whose field values the user cannot write is rejected, and so is a record the user cannot edit under sharing.
Handling failures
A user-mode operation signals a violation in one of two ways:
- A query, or DML with all-or-none behavior, throws an exception. Catch
QueryExceptionfor SOQL andDmlExceptionfor DML. - A
Databasemethod called withallOrNone = falsedoes not throw for access problems on individual records. Inspect eachSaveResultinstead.
public with sharing class SafeContactReader {
public static List<Contact> readOrEmpty(String lastName) {
try {
return [
SELECT Id, LastName, Email
FROM Contact
WHERE LastName = :lastName
WITH USER_MODE
];
} catch (QueryException e) {
// The user lacks access to the object or to a referenced field
System.debug(LoggingLevel.WARN, 'Access denied: ' + e.getMessage());
return new List<Contact>();
}
}
}Returning an empty list hides the problem from the caller, so do it only when an empty result is a sensible outcome for your feature. A common alternative is to rethrow as an AuraHandledException with a message the user can act on.
For results that must succeed even if some fields are hidden, Security.stripInaccessible is the other tool. It removes the fields the user cannot access and returns the cleaned records. It does not throw. User mode fails loudly. stripInaccessible degrades quietly. Choose based on whether a missing field should stop the operation.
Choosing the access level
The diagram shows how the pieces combine in one method. The class keyword sets the default for record sharing, and the access level on an operation can override it.
Edge cases and gotchas
- Only the marked operation is checked. A user-mode query returns data to code that is still in system mode. If that code then runs an unmarked DML statement, the DML runs with system permissions. Mark each operation that handles user-facing data.
- Relationship fields are checked too. A query such as
SELECT Account.Name FROM Contact WITH USER_MODEalso requires read access toAccount.Name. Users can be blocked by fields they never see in your UI. - Triggers and system tasks. Some operations must run in system mode, for example writing an audit log record the user has no permission to create. Keep those in a small, separate
without sharingclass. Do not drop user mode from the whole service to make one step work. - Aggregate and count queries.
SELECT COUNT() ... WITH USER_MODEcounts only visible records, so the number can differ from a system-mode count. This matters when the number drives a business decision. - Permissions are per user. A test that passes as an administrator proves nothing about a standard user. Test with
System.runAsand a user who holds only the intended permissions. The next chapters cover test design in more detail.
Summary of rules
- Use
with sharingas the class default for anything the user can reach. - Add user mode to each query and DML statement that reads or writes user-visible data.
- Handle
QueryExceptionandDmlException, or inspectSaveResultvalues for partial success. - Isolate unavoidable system-mode work in a narrow
without sharingclass with a comment explaining why.
Exercise
A without sharing service class runs [SELECT Id, Name FROM Account WITH USER_MODE] for a user who can read only some accounts and cannot read the Name field. What does the query do, and why?
Show answer
It throws a QueryException. User mode enforces object permissions, field-level security, and record-level sharing for that query, even though the class is without sharing. The user cannot read Name, so the query fails instead of returning any records. If the user could read Name, the query would return only the accounts the user's sharing access allows.
Exercise
You call Database.update(contacts, false, AccessLevel.USER_MODE) and the user lacks edit access on one record in the list. Does the method throw? How do you find the failure?
Show answer
With allOrNone set to false, the method does not throw for the single failed record. It returns a List<Database.SaveResult>. Loop through the results, check isSuccess(), and read getErrors() for the records that failed.