Sub topic 1
Apex Sharing Keywords: with sharing, without sharing, and inherited sharing
Prerequisites
You should know basic Apex classes, methods, and SOQL. You should also understand that organization-wide defaults, roles, and sharing rules control which Salesforce records a user can access.
Record-level sharing in a nutshell
Record-level sharing controls which individual records a user can view or change. For example, a user might have permission to read Account records but see only accounts owned by their team.
Apex can run in a different security context from the user. This difference matters when code queries or updates records.
Why Apex ignores sharing unless told otherwise
Apex runs in system context by default. System context means the code has broad access to records, so a SOQL query can return records that the running user could not normally see.
This default supports trusted automation, but it can expose data when code is called by a user-facing feature. Developers must choose a sharing mode deliberately.
What the sharing keywords control
A class can declare one of three sharing modes:
with sharingenforces the running user's record-level sharing.without sharingbypasses record-level sharing for that class.inherited sharinguses the sharing mode supplied by its caller, or runs with sharing when it is the entry point.
These keywords do not enforce object permissions or field-level security. Those controls require additional techniques, such as user-mode SOQL or DML.
with sharing: enforcing the user's record access
Use with sharing for controllers and services that act on behalf of a user. Queries and record operations then respect the user's record visibility.
public with sharing class AccountReader {
public static List<Account> getAccounts() {
return [SELECT Id, Name FROM Account];
}
}If the running user can see 20 Account records, this query returns only those accessible records. A with sharing declaration does not automatically grant access to records. It limits the class to records the user is already allowed to access.
Exercise
What does with sharing add to an Apex class?
Show answer
It makes the class respect the running user's record-level sharing when it accesses records.