Enforcing Sharing in Apex
By the end of this lesson, you'll be able to:
- Explain the difference between with sharing, without sharing, and inherited sharing
- Choose the correct sharing keyword for a given class
Prerequisites: Sharing Rules & Manual Sharing
System context by default
An Apex class with no sharing keyword — and a trigger, by default — runs in system mode: it ignores record-level sharing entirely and can see every record of an object it has permission to query. This is a deliberate default so ordinary business logic doesn't silently misbehave, but it means security-sensitive classes need to opt in explicitly.
with sharing, without sharing, inherited sharing
with sharing— enforces the running user's record-level sharing on every query and DML statement in the class.without sharing— explicitly runs in system mode, ignoring sharing. Useful for utility classes (like a scheduled cleanup job) that legitimately need to see everything.inherited sharing— adopts the sharing mode of whichever class called it. Ideal for reusable utility classes that should respect whatever context they're used in.
A common gotcha: a class with no keyword does not inherit sharing from its caller — it always runs in system mode unless declared with sharing (or inherited sharing) itself.
A sharing-aware service class
public with sharing class OpportunityService {
public static List<Opportunity> getOpenOpportunities() {
// Only returns Opportunities the running user can see
return [SELECT Id, Name, Amount FROM Opportunity WHERE IsClosed = false];
}
}
Because this class is declared with sharing, the SOQL query automatically filters out any Opportunity the running user doesn't have record-level access to — no extra WHERE clause needed.
Exercise
A class named ReportBuilder currently has no sharing keyword. Rewrite its declaration so it enforces the running user's sharing rules.
Show hint
Add the with sharing keyword between the access modifier and class.
Enforcing Sharing in Apex — 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
Apex classes run in system context (full record access) by default. Declaring a class with sharing enforces the running user's record-level sharing rules on every query and DML statement inside it; without sharing explicitly bypasses that enforcement.