WITH SECURITY_ENFORCED and StripInaccessible
By the end of this lesson, you'll be able to:
- Use WITH SECURITY_ENFORCED to enforce field- and object-level security on a SOQL query
- Use Security.stripInaccessible to sanitize a list of records before returning them
Prerequisites: Enforcing Sharing in Apex
WITH SECURITY_ENFORCED
Adding WITH SECURITY_ENFORCED to a SOQL query throws a System.NoAccessException at runtime if the running user lacks Field-Level Security access to any selected field, or object-level read access. It's an all-or-nothing check — ideal when you'd rather fail loudly than silently return incomplete data.
Security.stripInaccessible
Security.stripInaccessible is more forgiving: instead of throwing, it strips the fields (or whole records) the running user can't access from an already-fetched list, letting the rest of the operation continue cleanly. It's the standard way to sanitize a list of records right before returning them from an Apex REST endpoint or an LWC-facing @AuraEnabled method.
A field- and object-secured query
List<Account> accounts = [
SELECT Id, Name, AnnualRevenue
FROM Account
WITH SECURITY_ENFORCED
LIMIT 10
];
If the running user lacks read access to AnnualRevenue (or Account itself), this query throws a System.NoAccessException instead of silently returning the field anyway.
Exercise
Given a List<Contact> called contacts already queried without security enforcement, use Security.stripInaccessible to remove any fields the running user can't read before returning the list.
Show hint
SecurityDecision decision = Security.stripInaccessible(AccessType.READABLE, contacts); return decision.getRecords();
WITH SECURITY_ENFORCED and StripInaccessible — Quick Check
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
with sharing only enforces record-level access. WITH SECURITY_ENFORCED (in SOQL) and Security.stripInaccessible (in Apex) are the tools that additionally enforce field- and object-level security — the two layers with sharing does not touch.