Security & Sharing in Apex
CRUD & FLS Checks
What Are CRUD & FLS?
-
CRUD controls whether a user can Create, Read, Update, Delete records.
-
FLS (Field-Level Security) controls whether a user can see or edit specific fields.
Simple Explanation
CRUD decides which door you can enter,
FLS decides which drawers you can open inside the room.
Real-Life Example
A sales user:
-
Can read Accounts (CRUD)
-
Cannot edit Annual Revenue (FLS)
Code Example (CRUD + FLS)
if (Schema.sObjectType.Account.isCreateable() &&
Schema.sObjectType.Account.fields.Name.isUpdateable()) {
Account acc = new Account(Name = 'ABC Ltd');
insert acc;
}
Why This Matters
-
Prevents security violations
-
Required for Lightning, APIs, and managed packages
Gist (Quick Revision)
Always check whether the user is allowed to access objects and fields.
2. with sharing vs without sharing
What Is Sharing?
Sharing controls record-level access (which records a user can see).
with sharing
Respects:
-
Role hierarchy
-
Sharing rules
-
Manual sharing
public with sharing class AccountService {
// user-level record access applies
}
without sharing
Ignores record sharing rules.
public without sharing class AdminService {
// full record access
}
Real-Life Example
-
with sharing→ employee sees only their customers -
without sharing→ admin sees all customers
Easy Rule to Remember
with sharing = safer by default
Gist (Quick Revision)
Use with sharing unless you have a strong business reason not to.
3. Security.stripInaccessible
What Is Security.stripInaccessible?
Security.stripInaccessible() automatically removes fields and objects the user cannot access.
Why It’s Important
-
Prevents accidental data exposure
-
Reduces manual security checks
-
Best practice for APIs & Lightning
Code Example
List<Account> accs = [SELECT Name, AnnualRevenue FROM Account];
SObjectAccessDecision decision =
Security.stripInaccessible(
AccessType.READABLE, accs
);
List<Account> safeAccounts = (List<Account>) decision.getRecords();
Real-Life Example
If the user can’t see AnnualRevenue, Salesforce removes it automatically.
Gist (Quick Revision)
stripInaccessible protects data without complex security logic.
4. User Mode vs System Mode
What Is User Mode?
-
Respects user permissions
-
CRUD, FLS, and sharing apply
What Is System Mode?
-
Ignores user permissions
-
Default for Apex code
Why This Matters
Apex often runs with more power than the user, so developers must manually enforce security.
Example Scenario
A user cannot edit Account Revenue,
but Apex can—unless you add security checks.
Interview Tip
A strong answer:
“Apex runs in system mode, so we must enforce CRUD, FLS, and sharing explicitly.”
Gist (Quick Revision)
Apex runs with high privileges—security is the developer’s responsibility.
