Sub topic 11
Choosing the Right Enforcement Approach
This chapter helps you pick one way to enforce object and field permissions in Apex. It assumes you have read the earlier chapters on user mode, WITH USER_MODE, as user, AccessLevel, the older approaches, and failure handling. You should be comfortable with profiles, permission sets, CRUD, FLS, and sharing.
The options at a glance
Apex gives you several ways to respect the running user's permissions. They differ in what they check, how they fail, and how much code they need.
| Approach | Enforces CRUD and FLS | Enforces sharing | On failure | Applies to |
|---|---|---|---|---|
| `WITH USER_MODE` / `as user` / `AccessLevel.USER_MODE` | Yes, including fields in `WHERE`, `ORDER BY`, and relationship paths | Yes, regardless of the class's sharing keyword | Throws an exception, or returns per-record errors with `allOrNone` set to false | Queries and DML |
| `WITH SECURITY_ENFORCED` | Yes, but only for fields in `SELECT` and `FROM` | No, it follows the class's sharing keyword | Throws `QueryException` | Static SOQL only |
| `Security.stripInaccessible` | Yes, on the fields of records you pass in | No | Removes fields silently | Query results and records before DML |
| Describe checks (`isAccessible()`, `isCreateable()`, and so on) | Yes, but only where you write the check | No | You decide | Anything you code by hand |
| `with sharing` alone | No | Yes | Fewer rows returned | Records visible to the user |
The last row is the common mistake. A with sharing class filters rows. It does not check object permissions or field-level security.
Start from user mode
For new code, user mode is the default choice. It has three advantages over the alternatives:
- It is one keyword or one argument, so there is little room to forget a field.
- It checks the whole query.
WITH SECURITY_ENFORCEDignores fields used only inWHERE, which can let a user probe values in fields they cannot read. - It applies sharing and permissions together, so you do not rely on the class declaration to get row-level security.
The following class uses user mode for both the read and the write.
public with sharing class OpportunityService {
public static List<Opportunity> openOpportunities() {
return [
SELECT Id, Name, Amount, StageName
FROM Opportunity
WHERE IsClosed = false
WITH USER_MODE
ORDER BY CloseDate
LIMIT 100
];
}
public static void closeAsWon(List<Opportunity> opps) {
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
update as user opps;
}
}If the user lacks read access to IsClosed or CloseDate, the query fails. With WITH SECURITY_ENFORCED it would only have checked the four fields in the SELECT clause.
A decision flow
Work through the questions in order. Stop at the first one that applies.
The order matters. Most code belongs at E. The branches to G and H are exceptions that need a reason.
Choose by the shape of the operation
Static SOQL
Use WITH USER_MODE. It replaces WITH SECURITY_ENFORCED in nearly every case. Keep WITH SECURITY_ENFORCED only in code you do not want to touch, and note that it does not check sharing by itself.
Dynamic SOQL
Use Database.queryWithBinds with AccessLevel.USER_MODE. Bind variables also remove the need to concatenate user input into the query string, which prevents SOQL injection.
public with sharing class ContactSearch {
public static List<Contact> byLastName(String lastName) {
Map<String, Object> binds = new Map<String, Object>{ 'lastName' => lastName };
String soql = 'SELECT Id, LastName, Email FROM Contact WHERE LastName = :lastName';
return Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE);
}
}DML
Use insert as user, update as user, upsert as user, delete as user, or the Database overloads that take an AccessLevel. Choose between them like this:
- Use the keyword form when one failure should stop the whole transaction. It is the shortest form.
- Use
Database.insert(records, false, AccessLevel.USER_MODE)when you want per-record results. You then inspect eachDatabase.SaveResultand report which records failed.
public with sharing class LeadImporter {
public static List<String> importLeads(List<Lead> leads) {
List<String> errors = new List<String>();
List<Database.SaveResult> results =
Database.insert(leads, false, AccessLevel.USER_MODE);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
errors.add('Row ' + i + ': ' + err.getMessage());
}
}
}
return errors;
}
}Records that arrive from somewhere else
Sometimes you do not control the query or the DML. A record might come from a callout, a method parameter, or a cached collection. Then Security.stripInaccessible is a good fit. It filters the record, so the caller never sees fields the user cannot read, and you can call it with AccessType.CREATABLE or AccessType.UPDATABLE before DML.
public with sharing class AccountPrep {
public static List<Account> prepareForUpdate(List<Account> incoming) {
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.UPDATABLE, incoming);
return (List<Account>) decision.getRecords();
}
}This silently drops fields the user cannot edit. That is correct for a form where the user may not see every field. It is wrong for an integration where a missing value should be an error.
Fail loudly or degrade quietly
The most useful question is what you want to happen when access is missing.
| Goal | Approach | Result |
|---|---|---|
| Reject the request and tell the user | User mode | An exception such as `QueryException` or `DmlException` |
| Handle each record separately | `Database` DML with `allOrNone` false and user mode | A `SaveResult` per record |
| Show what the user is allowed to see | `Security.stripInaccessible` | Records with fewer fields |
| Apply custom rules, such as hiding one UI section | Describe checks | Your own branching |
Silent stripping can hide bugs. A field that is stripped for a low-privilege user may show up as null, and later code may treat that as real data. If your code reads a field after stripInaccessible, check whether the user could read it first, for example with decision.getRemovedFields().
Gotchas when mixing approaches
- Do not stack them without a reason. Adding
WITH SECURITY_ENFORCEDto a query that already hasWITH USER_MODEis not allowed in the same query. Pick one. - Sharing keywords still matter for system-mode code. User mode enforces sharing for the operation it covers. Other queries in the same class still follow the class declaration. Declare
with sharinganyway so uncovered code does not default to a looser mode. - Triggers run in system mode. A trigger that calls a user mode query inside a helper class works. A trigger body itself does not enforce permissions.
- Describe checks do not scale. Each field needs its own check, and a forgotten field leaves a gap. Reserve them for conditional logic, not blanket enforcement.
- Test as the right user. Tests run in system mode, so an approach that appears to work in a test may never have been exercised against a restricted user. Use
System.runAsto verify the enforcement.
Migrating existing code
When you maintain older code, you do not need to rewrite everything at once. A practical order is:
- Find queries that use
WITH SECURITY_ENFORCEDand switch them toWITH USER_MODE. Expect failures in cases where aWHEREorORDER BYfield was never checked. - Find DML that is preceded by a block of
isCreateable()orisUpdateable()checks. Replace it withas userwhere the failure behavior is acceptable. - Find dynamic SOQL built by string concatenation. Move it to
Database.queryWithBindswithAccessLevel.USER_MODE. - Leave
stripInaccessiblein place where silent filtering is the intended behavior. - Add
System.runAstests for each changed method before you merge.
Change one class at a time. A switch to user mode can expose permission gaps that earlier code hid, so some users may start to see errors until their permission sets are corrected.
Exercise
A service method reads Account records for an Aura component. Some users do not have read access to the AnnualRevenue field. The product owner says the page should still load for those users and simply leave that value out. Which approach fits, and what must you check before using the field later?
Show answer
Use Security.stripInaccessible(AccessType.READABLE, records), because the page should degrade instead of fail. User mode would throw a QueryException for those users. Before using AnnualRevenue, check whether it was removed, for example with decision.getRemovedFields(), because a stripped field reads as null and can be mistaken for an empty value.
Exercise
A query uses WITH SECURITY_ENFORCED and selects only Id and Name, but its WHERE clause filters on a field the user cannot read. What happens, and what happens if you change it to WITH USER_MODE?
Show answer
With WITH SECURITY_ENFORCED the query runs, because only fields in the SELECT clause are checked, so the user can learn about values in a hidden field through the filter. With WITH USER_MODE the WHERE field is checked too, so the query throws a QueryException.
Exercise
You import 200 leads from a CSV and want valid rows saved while rows the user cannot create are reported back. Write the DML call.
Show answer
List<Database.SaveResult> results = Database.insert(leads, false, AccessLevel.USER_MODE); Setting allOrNone to false allows partial success, and user mode enforces create permission and FLS. Loop over results and call getErrors() on each failed result to report the problems.