Security.stripInaccessible
By the end of this lesson, you'll be able to:
- Use Security.stripInaccessible to automatically remove fields a user can't access
- Explain the problem this method solves compared to manual field checks
- Apply it before both reading and writing sObject data
Prerequisites: "CRUD and Field-Level Security"
The problem: manual checks don't scale
// Checking every field individually is tedious and easy to forget one
if (Schema.sObjectType.Account.fields.Name.isAccessible()) { /* ... */ }
if (Schema.sObjectType.Account.fields.Industry.isAccessible()) { /* ... */ }
if (Schema.sObjectType.Account.fields.AnnualRevenue.isAccessible()) { /* ... */ }
// ...and so on, for every field a query touches
For a query selecting 10 fields, this means 10 separate checks — tedious to write, and easy to accidentally miss one when a query changes later.
The one-line fix
List<Account> accounts = [SELECT Id, Name, Industry, AnnualRevenue FROM Account];
SObjectAccessDecision decision = Security.stripInaccessible(AccessType.READABLE, accounts);
List<Account> safeAccounts = decision.getRecords();
Security.stripInaccessible(AccessType.READABLE, accounts) checks every field on every record against the running user's actual field-level security, and returns a cleaned-up version with inaccessible fields automatically removed — no per-field manual checking required.
Using it before a write, too
Account acc = new Account(Name = 'Riverbend Farms', AnnualRevenue = 5000000);
SObjectAccessDecision decision = Security.stripInaccessible(AccessType.CREATABLE, new List<Account>{acc});
List<Account> safeToInsert = decision.getRecords();
insert safeToInsert;
The same method works before an insert or update too, with AccessType.CREATABLE or AccessType.UPDATABLE — stripping out any field the user isn't actually allowed to set, before the DML statement runs at all.
Exercise
Given a List<Contact> contacts already queried, use Security.stripInaccessible with AccessType.READABLE and get the cleaned records.
Show hint
Security.stripInaccessible(AccessType.READABLE, contacts).getRecords()
Security.stripInaccessible Quiz
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
Manually checking every single field's accessibility (previous lesson) doesn't scale — Security.stripInaccessible automatically strips out fields the running user can't access from a query result or a record about to be saved.