Sub topic 10
Older approaches: SECURITY_ENFORCED, stripInaccessible, describe checks
This chapter assumes you can read and write static SOQL and DML in Apex. It also assumes you know the difference between sharing rules and object and field permissions, and that you know what WITH USER_MODE and as user do from the earlier chapters. You need to understand the older enforcement tools because most existing orgs still use them. You will often have to read them, review them, or decide whether to migrate them.
Why the older tools exist
User mode was added to Apex after several other mechanisms. Teams had to enforce object permissions and field-level security (FLS) long before user mode existed, so three techniques became standard:
WITH SECURITY_ENFORCED, a SOQL clause for reads.Security.stripInaccessible, a method that removes fields from records.- Schema describe checks, such as
isAccessible()andisCreateable().
Each one solves part of the problem. None of them covers everything that user mode covers.
WITH SECURITY_ENFORCED
WITH SECURITY_ENFORCED is a SOQL clause. It checks that the running user can read the object and the fields that appear in the query. If any check fails, the query throws a System.QueryException.
public with sharing class LegacyAccountQuery {
public static List<Account> getAccounts() {
try {
return [
SELECT Id, Name, Industry
FROM Account
WHERE Industry != null
WITH SECURITY_ENFORCED
LIMIT 50
];
} catch (QueryException e) {
System.debug(LoggingLevel.WARN, 'Access denied: ' + e.getMessage());
throw new AuraHandledException('You do not have access to this data.');
}
}
}The clause goes after WHERE and before ORDER BY and LIMIT. It has these limits:
- Fields in
WHEREandORDER BYare not checked. A user who cannot readIndustrycan still filter on it. The results can leak information about the hidden field's values. - It only checks reads. There is no matching clause for
insert,update,upsert, ordelete. - It does not enforce sharing. Sharing still comes from the
with sharingkeyword on the class. - It stops at the first failure. The exception names one inaccessible field, even if several are blocked. Users and admins fix the problem one field at a time.
- It cannot be combined with user mode. A query cannot contain both
WITH SECURITY_ENFORCEDandWITH USER_MODE.
The first limit is the most common reason teams migrate. WITH USER_MODE also checks fields used in WHERE.
// Same query, stricter checks: fields in WHERE are verified too.
List<Account> accounts = [
SELECT Id, Name, Industry
FROM Account
WHERE Industry != null
WITH USER_MODE
LIMIT 50
];Security.stripInaccessible
Security.stripInaccessible takes a list of records and returns a copy with the fields the user may not access removed. It does not throw because of a blocked field. This fits cases where partial data is acceptable, such as displaying a record with some fields missing.
public with sharing class StripReadExample {
public static List<Account> readableOnly(List<Account> records) {
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.READABLE, records);
return (List<Account>) decision.getRecords();
}
}The AccessType value selects the permission to test:
| AccessType | Checks | Typical use |
|---|---|---|
| `READABLE` | Field read access | Data from a query before you return it |
| `CREATABLE` | Field create access | Records before `insert` |
| `UPDATABLE` | Field edit access | Records before `update` |
| `UPSERTABLE` | Create and edit access | Records before `upsert` |
The SObjectAccessDecision object gives you three things:
getRecords()returns the cleaned records.getRemovedFields()returns aMap<String, Set<String>>. The keys are object names and the values are the removed field names.getModifiedIndexes()returns the positions of the records that had fields removed.
Stripping before DML
You can also strip records before DML. The records you pass in are not changed. You use the returned copy.
public with sharing class ContactSaver {
public static void save(List<Contact> contacts) {
try {
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.CREATABLE, contacts);
insert decision.getRecords();
Map<String, Set<String>> removed = decision.getRemovedFields();
if (removed.containsKey('Contact')) {
System.debug(LoggingLevel.WARN,
'Fields dropped on insert: ' + removed.get('Contact'));
}
} catch (NoAccessException e) {
throw new AuraHandledException('You cannot create contacts.');
}
}
}This code shows the main risk of the method. A user who cannot set Email still has a successful insert. The email value is silently dropped. If you do not inspect getRemovedFields(), the caller thinks everything saved correctly.
Gotchas
- Object-level access is checked by default. If the user lacks the object permission, the method throws a
System.NoAccessException. A second overload takes anenforceRootObjectCRUDboolean. Setting it tofalseskips that check, which can hide a permission problem. - Stripped fields cannot be read. Reading a removed field on the returned record throws an
SObjectException, because the field is now absent from the record. Code that expects the field to benullbreaks. - It runs after the query. It cannot protect a
WHEREclause. Records are already filtered by a field the user may not be allowed to read. - It does not enforce sharing. The query still needs
with sharingor user mode for record visibility. - It works on records you already hold. The query runs in whatever mode the class is in. If the code retrieves more records than the user should see, stripping fields does not remove those records.
Describe checks
Describe checks are the oldest approach. You ask the schema whether the current user may perform an operation, then branch in your own code.
public with sharing class DescribeCheckExample {
public static List<Account> getAccounts() {
if (!Schema.SObjectType.Account.isAccessible()
|| !Schema.SObjectType.Account.fields.Name.isAccessible()
|| !Schema.SObjectType.Account.fields.Industry.isAccessible()) {
throw new AuraHandledException('You do not have access to this data.');
}
return [SELECT Id, Name, Industry FROM Account LIMIT 50];
}
public static void createAccount(String name, String industry) {
if (!Schema.SObjectType.Account.isCreateable()
|| !Schema.SObjectType.Account.fields.Name.isCreateable()
|| !Schema.SObjectType.Account.fields.Industry.isCreateable()) {
throw new AuraHandledException('You cannot create accounts.');
}
insert new Account(Name = name, Industry = industry);
}
}The available methods map to the operations:
| Method | Meaning |
|---|---|
| `isAccessible()` | The user can read the object or field |
| `isCreateable()` | The user can create the object or set the field on insert |
| `isUpdateable()` | The user can edit the object or field |
| `isDeletable()` | The user can delete records (object only) |
Describe checks give you full control over the error message and the logic. That control has a cost:
- They are verbose. Every field in every query and DML statement needs its own check.
- They go stale. If a developer adds a field to the query and forgets the matching check, the code compiles and passes tests. The hole appears only for a user without access.
- They check access, not data. The check happens in a separate step from the query. Nothing ties the checks to what the query really uses.
- They do not enforce sharing. Record visibility is still decided by
with sharing. - Relationship fields need extra work. A query like
SELECT Account.Owner.Name FROM Contacthas to be checked on each object and field along the path.
Describe checks still have a place. Use them when you need to ask a permission question without running a query, for example to hide a button in a UI or to decide which columns to show.
Comparing the approaches
The following table compares the older tools with user mode.
| Capability | User mode | SECURITY_ENFORCED | stripInaccessible | Describe checks |
|---|---|---|---|---|
| Object read check | Yes | Yes | Yes (default) | Manual |
| Field read check in `SELECT` | Yes | Yes | Yes | Manual |
| Field check in `WHERE` | Yes | No | No | Manual |
| Enforces DML permissions | Yes | No | Yes, via strip before DML | Manual |
| Enforces sharing | Yes | No | No | No |
| Failure style | Exception | Exception | Silent removal | Your own logic |
| Amount of code | Low | Low | Medium | High |
Of these, only user mode applies the running user's permissions to the whole operation, including sharing, in one keyword or one argument. The others enforce parts of it.
Migrating to user mode
For most code the migration is mechanical. Swap the clause, then test the failure path.
| Before | After |
|---|---|
| `... WITH SECURITY_ENFORCED` | `... WITH USER_MODE` |
| Describe checks followed by `insert c;` | `insert as user c;` |
| `stripInaccessible` followed by `insert` | `Database.insert(records, false, AccessLevel.USER_MODE)` when you want per-record results |
public with sharing class ContactServiceAfter {
public static void createContact(String lastName, String email) {
Contact c = new Contact(LastName = lastName, Email = email);
insert as user c;
}
}Check these points before you finish a migration:
- Stricter
WHEREchecks. The migrated query may now fail for users who could previously run it, because user mode checks filter fields too. This is the intended fix, but you may see new errors. - Sharing changes.
SECURITY_ENFORCEDdid not apply sharing, and user mode does. Users may see fewer rows. - Failure behavior. Code that relied on
stripInaccessibleto continue silently now throws. Decide whether the caller should see an error or whether you still want the partial behavior. - Tests. Confirm the new behavior with
System.runAs, as shown in the testing chapter.
Common errors
- Assuming
WITH SECURITY_ENFORCEDprotectsWHEREfields. It does not. - Reading a stripped field on the returned record and getting an
SObjectException. - Calling
insert recordswith the original list afterstripInaccessible. This bypasses the cleaned copy. - Passing
falseforenforceRootObjectCRUDto silence aNoAccessException, which removes the object check. - Adding a field to a query and forgetting the describe check for it.
- Treating
with sharingas field-level security. It controls record visibility only.
Exercise
A class uses WITH SECURITY_ENFORCED to query Account and filters with WHERE Rating = 'Hot'. A user has read access to Account and Name but not to the Rating field. The query succeeds for this user. Why, and what change closes the gap?
Show answer
WITH SECURITY_ENFORCED checks only the fields in the SELECT list, not fields used in WHERE. The user can therefore filter on Rating without being able to read it, which leaks information about its values. Replacing the clause with WITH USER_MODE checks the WHERE field too, so the query throws a QueryException for this user.
Exercise
Code calls Security.stripInaccessible(AccessType.CREATABLE, contacts) and then runs insert contacts; using the original list. What goes wrong, and what is the correct call?
Show answer
The original list still contains the values the user is not allowed to set, so the strip has no effect and the insert writes those fields. The code must insert the cleaned records with insert decision.getRecords();. It should also inspect decision.getRemovedFields() so the caller knows which values were dropped.