Sub topic 4
with sharing: enforcing the user's record access
This chapter assumes you can read basic Apex (classes, methods, SOQL) and know how organization-wide defaults, roles, and sharing rules decide who sees a record. It also assumes you know what profiles and permission sets are. The earlier chapters explained why Apex runs in system context by default. Here you will see what the with sharing keyword changes, what it leaves alone, and how to confirm it works.
What the keyword does
Declaring a class with sharing tells Apex to apply the running user's record-level sharing to the SOQL, SOSL, and DML statements in that class. "Record-level sharing" covers everything that grants access to individual records:
- Organization-wide defaults
- Role hierarchy
- Sharing rules
- Manual shares
- Account, opportunity, and case teams
- Apex managed sharing
The "running user" is whoever started the transaction, such as the person clicking in a Lightning page, or the user a REST call authenticated as.
Here is the minimal form, the same one used in the series overview:
public with sharing class AccountReader {
public static List<Account> getAccounts() {
// Returns only the Account records the running user can see
return [SELECT Id, Name FROM Account];
}
}The class has no special code for filtering. The platform adds the sharing check to the query for you. If the user can see 40 of 10,000 accounts, the list has at most 40 rows.
What happens on a query
Queries in a with sharing class never raise an error for records the user cannot see. The records are left out of the result, with no warning. This has three practical effects.
- A list query returns fewer rows than exist. Aggregates such as
COUNT()andSUM()are computed only over visible rows. - A query by Id returns an empty list when the user lacks access.
- Assigning a query straight to a single record throws a
QueryException("List has no rows for assignment to SObject") when that record is hidden.
The third effect is a common source of confusing bugs. Prefer a list and check it:
public with sharing class AccountLookup {
public static Account findById(Id accountId) {
List<Account> rows = [SELECT Id, Name FROM Account WHERE Id = :accountId];
return rows.isEmpty() ? null : rows[0];
}
}A null result here can mean the record does not exist, or it exists and the user cannot see it. Sharing deliberately does not tell you which.
What happens on DML
DML behaves differently from queries. If the user lacks the access needed to change a record, the statement fails with a DmlException. For edit and delete, the status code is usually INSUFFICIENT_ACCESS_OR_READONLY.
public with sharing class AccountUpdater {
public static Boolean tryRename(Id accountId, String newName) {
Account acc = new Account(Id = accountId, Name = newName);
try {
update acc;
return true;
} catch (DmlException e) {
if (e.getDmlType(0) == StatusCode.INSUFFICIENT_ACCESS_OR_READONLY) {
return false;
}
throw e;
}
}
}Handle only the status codes you expect and rethrow the rest. Swallowing every DmlException would hide validation rule failures and other real problems.
If you use partial-success methods such as Database.update(records, false), the failure is reported in the SaveResult for that record instead of as an exception. Check isSuccess() and getErrors() on each result.
What it covers and what it does not
The keyword affects the code written in the class that declares it. It does not make the whole transaction run as the user in every respect.
| Aspect | Enforced by `with sharing`? |
|---|---|
| Record visibility on SOQL and SOSL | Yes |
| Record access checks on DML | Yes |
| Object permissions (create, read, edit, delete) | No |
| Field-level security | No |
| Sharing inside classes called from this one | Decided by each called class |
| Validation rules, triggers, and flows fired by DML | Run as usual. A trigger's own code runs in system mode, so only a class it calls can enforce sharing |
| "View All Data" and "Modify All Data" | Honored, so users with them still see everything |
| "View All" and "Modify All" on a single object | Honored for that object |
Two rows deserve emphasis.
First, with sharing is not a substitute for permission checks. A user whose profile has no read access to Contact can still have a with sharing class return Contact rows, because object permissions are a separate layer. The same goes for fields. A later chapter covers this and the user-mode queries and DML that enforce those permissions.
Second, "enforcing the user's access" includes the user's elevated permissions. An administrator with View All Data sees every record through a with sharing class. That is correct behavior, and it matters when you write tests, because an admin test user will not show any filtering.
Where the keyword goes and how far it reaches
You can put with sharing on top-level classes, and that includes classes that act as entry points: Lightning controllers, REST resources, batch jobs, queueable and schedulable classes, and invocable methods. The sharing mode is decided by the class where the executing code is defined, not by the class that happens to be the entry point. Triggers cannot declare a keyword. A trigger's own code runs in system mode, so move record-access-sensitive logic into a handler class and declare that class's mode explicitly.
When a with sharing class calls a method in another class, that other class's own keyword decides what happens inside it. A without sharing class called from a with sharing class still bypasses sharing inside its own methods. A class with no keyword takes on the mode of the class calling it. A later chapter works through these call chains in detail.
Inner classes do not inherit the keyword from their outer class. Declare it on the inner class too when it contains queries or DML.
Verifying it in a test
Sharing is easiest to understand once you have watched it filter data. The test below assumes the organization-wide default for Account is Private, which is the case in most scratch orgs only if you set it. Check Setup > Sharing Settings first.
@IsTest
private class AccountReaderTest {
private static User buildUser(Id profileId, String tag) {
String unique = tag + String.valueOf(Crypto.getRandomInteger()).replace('-', 'n');
return new User(
LastName = 'Tester ' + tag,
Alias = tag.left(5),
Email = unique + '@example.com',
Username = unique + '@example.com.sharingtest',
ProfileId = profileId,
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US'
);
}
@IsTest
static void usersDoNotSeeRecordsOwnedByPeers() {
Profile standard = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User owner = buildUser(standard.Id, 'owner');
User peer = buildUser(standard.Id, 'peer');
insert new List<User>{ owner, peer };
System.runAs(owner) {
insert new Account(Name = 'Private Account');
System.assertEquals(1, AccountReader.getAccounts().size(), 'Owner sees own record');
}
System.runAs(peer) {
System.assertEquals(0, AccountReader.getAccounts().size(), 'Peer is filtered out');
}
}
}System.runAs switches the running user, and with sharing applies that user's access. The same test run against a without sharing class would return one row for both users, which is a quick way to prove which mode a class really has.
Choosing with sharing
Use with sharing as the starting point for any class that handles data on behalf of a user. That includes @AuraEnabled controllers, REST resources, and service classes called from them. Most security review findings come from classes that should have declared it and did not. Switch to without sharing only for a specific, documented reason, and keep that code small. Later chapters cover that decision and the inherited sharing option for reusable classes.
Common mistakes
- Treating a
nullor empty result as "record does not exist". With sharing, it can also mean "you may not see it". - Assigning a query directly to a single sObject variable and getting a
QueryExceptionfor hidden records. - Assuming
with sharingblocks access to objects or fields the user's profile denies. It does not. - Testing as an administrator, where View All Data hides the effect.
- Forgetting that inner classes need their own keyword.
- Catching
Exceptionbroadly around DML and masking sharing failures.
Exercise
A user has read access to the Contact object but cannot see a particular contact because of the sharing model. A with sharing method runs Contact c = [SELECT Id FROM Contact WHERE Id = :hiddenId];. What happens, and how would you rewrite the code to handle it?
Show answer
The query returns no rows, and assigning an empty result to a single Contact throws a QueryException ("List has no rows for assignment to SObject"). Query into a List<Contact> instead, check isEmpty(), and handle the "not found or not visible" case, for example by returning null or showing a message.
Exercise
A with sharing class uses update on an Account record the user can see but not edit. The user's profile does have Edit permission on the Account object. What does the platform do, and which layer decided it?
Show answer
The update fails with a DmlException, typically with status code INSUFFICIENTACCESSOR_READONLY. Object permission allowed editing in general, but record-level sharing gave the user read-only access to this specific record, and with sharing applies that record-level check to DML.