Sub topic 11
Enforcing FLS with WITH USER_MODE and AccessLevel.USER_MODE
This chapter assumes you know basic Apex and SOQL, that you understand object permissions and field-level security (FLS) as set through profiles and permission sets, and that you know Apex runs in system mode by default. Here you will learn how to make queries and DML (data manipulation language: insert, update, delete) respect the running user's access.
What user mode changes
Apex normally runs in system mode. A query in system mode ignores the running user's object permissions, FLS, and sharing rules. That is why a user without access to a field can still cause your code to read it.
User mode reverses this for a single operation. The platform checks three things against the running user:
- Object permissions (CRUD): can the user read, create, edit, or delete this object?
- Field-level security: can the user read or edit each field the operation touches?
- Sharing rules: which records can the user see?
User mode applies to the whole operation, including fields in WHERE and ORDER BY clauses and in subqueries and relationship paths. If any part of the operation touches something the user cannot access, the operation fails.
User-mode SOQL with WITH USER_MODE
Add WITH USER_MODE to a static SOQL query:
List<Account> accounts = [
SELECT Id, Name, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
WITH USER_MODE
];If the user cannot read AnnualRevenue, or cannot read Industry, the query throws a System.QueryException. It does not silently drop the field. The exception message names the inaccessible field, so you can catch it and respond:
try {
List<Account> accounts = [
SELECT Id, Name, AnnualRevenue
FROM Account
WITH USER_MODE
];
} catch (QueryException e) {
System.debug(LoggingLevel.ERROR, 'Query blocked: ' + e.getMessage());
}The clause goes after WHERE and before GROUP BY, ORDER BY, and LIMIT. Bind variables work as usual.
For dynamic SOQL, pass the access level as the second argument:
String fieldList = 'Id, Name, AnnualRevenue';
List<Account> accounts = Database.query(
'SELECT ' + fieldList + ' FROM Account',
AccessLevel.USER_MODE
);Database.queryWithBinds also accepts an access level, and it is the safer choice when your query includes user-supplied values:
Map<String, Object> binds = new Map<String, Object>{ 'industry' => 'Technology' };
List<Account> accounts = Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Industry = :industry',
binds,
AccessLevel.USER_MODE
);User-mode DML with AccessLevel.USER_MODE
The Database class methods for DML take an AccessLevel argument:
Account acc = new Account(Name = 'Acme', AnnualRevenue = 1000000);
Database.insert(acc, AccessLevel.USER_MODE);The platform checks that the user can create Account and can edit every field you set on the record. If the user lacks edit access to AnnualRevenue, the insert fails. The same pattern covers Database.update, Database.upsert, Database.delete, Database.undelete, and Database.merge.
The overloads that take allOrNone also accept an access level:
List<Account> toInsert = new List<Account>{
new Account(Name = 'Acme'),
new Account(Name = 'Globex', AnnualRevenue = 500000)
};
List<Database.SaveResult> results = Database.insert(toInsert, false, AccessLevel.USER_MODE);
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
System.debug(err.getStatusCode() + ': ' + err.getMessage());
}
}
}With allOrNone set to false, a field-access failure appears as an error on the individual SaveResult instead of an exception. Check the results, or you will miss failures.
The standalone keywords insert as user, update as user, and so on do the same job:
insert as user new Account(Name = 'Acme');How the pieces compare
| Operation | System mode (default) | User mode |
|---|---|---|
| Static SOQL | No clause | `WITH USER_MODE` |
| Dynamic SOQL | `Database.query(q)` | `Database.query(q, AccessLevel.USER_MODE)` |
| DML | `insert acc;` | `Database.insert(acc, AccessLevel.USER_MODE)` or `insert as user acc;` |
| Failure behavior | Never fails on access | Throws, or returns errors in `SaveResult` |
Failure behavior and what to do about it
User mode is strict by design. A query that selects ten fields fails if the user cannot read one. This protects data, but it means your code must decide what to do when access is missing. You have three options:
- Let the exception propagate. This suits internal services where missing access means a configuration problem.
- Catch it and return a clear message to the user.
- Use
Security.stripInaccessibleinstead, which removes unreadable fields and continues. The next chapter covers it.
Avoid catching the exception and then re-running the same query in system mode. That defeats the check.
Edge cases and gotchas
- Trigger and system processes. User mode uses the running user. In a scheduled job or a trigger fired by an integration, that is the job owner or the integration user, whose access may differ from what you expect.
- Related records. Relationship fields such as
Account.Owner.Namerequire read access to the related object and field. A missing permission on the parent fails the whole query. - Aggregate queries. Fields used in
GROUP BYand in aggregate functions are checked too. - Mixing modes. A user-mode call inside a system-mode class still checks the user. A system-mode call inside a user-mode context still bypasses checks. Mode is a property of each statement, not of the call stack.
- Triggers and cascading effects. Database triggers, workflow field updates, and other automation still run in system context after a user-mode DML succeeds. User mode checks the statement you wrote, not what automation does afterward.
- Class-level keywords.
with sharinggoverns record visibility only. It does not enforce FLS or CRUD. Do not treat it as a substitute.
Choosing between approaches
Prefer user mode as your default for code that acts on behalf of a user, such as @AuraEnabled methods, REST resources, and Visualforce controllers. It is concise, checked by the platform, and keeps your code short. Compared with schema describe checks, it needs no per-field code and cannot go out of date when someone adds a field.
Keep system mode for work that must run regardless of the user's access, such as a rollup that writes to a field users cannot see. Document these cases, and keep the system-mode code small.
Testing the behavior
Use System.runAs to run a test as a user without field access. This test builds on a Standard User whose profile cannot read a custom field:
@IsTest
private class AccountUserModeTest {
@IsTest
static void queryFailsWhenFieldIsHidden() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tstusr',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tstusr' + System.currentTimeMillis() + '@example.com'
);
insert u;
Boolean blocked = false;
System.runAs(u) {
try {
Database.query('SELECT Id, Internal_Notes__c FROM Account', AccessLevel.USER_MODE);
} catch (QueryException e) {
blocked = true;
}
}
Assert.isTrue(blocked, 'The query should fail when the user cannot read the field');
}
}The test assumes Internal_Notes__c exists in your org and that no permission set gives the Standard User profile access to it. Without those conditions the assertion fails.
Common mistakes
- Adding
WITH USER_MODEto the query but writing the DML in system mode. Secure both reads and writes. - Using the older
WITH SECURITY_ENFORCEDin new code. User mode is the newer feature. It also checks fields inWHEREand enforces sharing, whichWITH SECURITY_ENFORCEDdoes not do for sharing. - Ignoring
SaveResulterrors whenallOrNoneisfalse. - Testing only as an administrator, who typically has access to everything, so the test never exercises a failure path.
Exercise
A class is declared without sharing. It contains the query [SELECT Id, Name FROM Account WITH USER_MODE]. The running user can read Account and Name but can see only some Account records through sharing. What does the query return, and why?
Show answer
It returns only the Account records the user can see through sharing rules. User mode enforces sharing for that statement even though the class is without sharing, and the user has read access to the object and to both fields, so no exception is thrown.
Exercise
You call Database.update(records, false, AccessLevel.USER_MODE) and the user lacks edit access to one field you changed. No exception is thrown, yet the data is not saved. Where do you find the failure?
Show answer
In the returned List<Database.SaveResult>. With allOrNone set to false, each failed record has a SaveResult where isSuccess() is false, and getErrors() describes the field-access problem.