Sub topic 10
Sharing is not CRUD or field-level security
This chapter assumes you can write basic Apex classes and SOQL queries. It also assumes you know organization-wide defaults, roles, and sharing rules, and that you know profiles and permission sets exist. By the end, you should be able to say which of Salesforce's access controls a sharing keyword enforces and which it does not.
Three separate layers of access
Salesforce decides what a user can do with data at three levels. Each level answers a different question.
| Layer | Question it answers | Controlled by |
|---|---|---|
| Object permissions (CRUD) | Can the user create, read, edit, or delete records of this object at all? | Profiles and permission sets |
| Field-level security (FLS) | Can the user see or edit this field? | Profiles and permission sets |
| Record-level sharing | Can the user access this particular record? | Organization-wide defaults, role hierarchy, sharing rules, manual shares, teams |
The sharing keywords (with sharing, without sharing, inherited sharing) touch only the third layer. They tell Apex whether to apply the running user's record-level access when it runs SOQL queries and DML. They do not turn on object permission checks. They do not turn on field-level security checks.
The default for Apex is system context. Code runs with broad access to objects and fields, and the sharing keyword only changes the record-level part.
What with sharing does and does not do
Look at this class again.
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];
}
}Suppose the running user's profile has no Read permission on Account. You might expect the query to fail. It does not. The query still runs in system context for object and field access. Record-level sharing is applied, so the result contains only records the user's sharing allows. If the user's profile lacks Account access, the user still gets those rows.
The same applies to fields. Suppose the user has no field-level access to Account.AnnualRevenue. This query still returns the value:
public with sharing class RevenueReader {
public static List<Account> getRevenue() {
return [SELECT Id, Name, AnnualRevenue FROM Account];
}
}with sharing limits which rows come back. It does not remove columns the user cannot see.
A worked comparison
Consider one user and one query, and watch which layer changes the result.
Assume the following:
- The user's profile has Read on Contact.
- The profile hides
Contact.Emailthrough field-level security. - Organization-wide default for Contact is Private, and the user can see only 10 of 100 contacts.
| Code | Rows returned | Includes Email values? |
|---|---|---|
| `without sharing` class, plain SOQL | 100 | Yes |
| `with sharing` class, plain SOQL | 10 | Yes |
| `with sharing` class, `WITH USER_MODE` | 10 | Query fails because the user cannot read Email |
| `without sharing` class, `WITH USER_MODE` | 10 | Query fails because the user cannot read Email |
The last row is worth noting. User mode applies the user's record access as well. When a query runs in user mode, record-level sharing is enforced regardless of the class keyword. This is covered in the next chapter in detail, so here we only use it to show the contrast.
How the layers combine
The diagram shows what each choice adds to a query. Each step moves toward stricter enforcement.
Enforcing CRUD and FLS
Apex gives you three common tools for object and field checks. They differ in how much code you write and how complete they are.
- User mode on queries and DML. The newest and simplest option. Add
WITH USER_MODEto a query, or passAccessLevel.USER_MODEto aDatabasemethod. WITH SECURITY_ENFORCED. An older clause on SOQL. It throws an exception if the user cannot read a queried field. It checks only the fields in theSELECTclause, not those inWHERE, and it does not cover DML.- Describe checks and
Security.stripInaccessible. Manual calls such asSchema.sObjectType.Contact.isAccessible(), or stripping inaccessible fields from a record list before use.
For new code, prefer user mode. Here is the pattern from the topic's example:
public with sharing class ContactService {
public static List<Contact> getContacts() {
// with sharing limits the records; USER_MODE also enforces object and field permissions
return [SELECT Id, LastName, Email FROM Contact WITH USER_MODE];
}
public static void saveContacts(List<Contact> contacts) {
Database.update(contacts, AccessLevel.USER_MODE);
}
}If the running user cannot read Contact.Email, the query throws a System.QueryException. If the user cannot edit a field in the records passed to saveContacts, the update fails with a System.DmlException. The failure is explicit, so you find permission gaps during testing instead of in production.
Handling the failure gracefully
You may prefer to return partial data instead of failing. In that case, Security.stripInaccessible removes fields the user cannot read.
public with sharing class ContactSafeReader {
public static List<Contact> getReadableContacts() {
List<Contact> rows = [SELECT Id, LastName, Email FROM Contact];
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.READABLE, rows);
return (List<Contact>) decision.getRecords();
}
}The returned records have the inaccessible fields removed, so reading Email on a record from a user without access throws a System.SObjectException unless you check with isSet-style logic or avoid the field. Choose this approach when partial results are acceptable. Choose user mode when a permission gap should stop the operation.
Common mistakes
- Treating
with sharingas a complete security control. It covers records only. Add user mode, or an equivalent check, for objects and fields. - Assuming a missing profile permission blocks Apex. Apex in system context ignores most of what profiles and permission sets grant. A user with no object access can still trigger code that reads the object.
- Using
without sharingto "fix" a field error. Field errors come from FLS or user mode, not from sharing. Switching the keyword changes which rows are returned and does not address field permissions. - Expecting user mode to depend on the class keyword. User mode enforces record access itself, as the worked comparison shows. Declaring
with sharingon the class is still good practice, because it covers any plain queries in the same class. - Forgetting that triggers and other entry points differ. Lightning components calling
@AuraEnabledmethods, REST resources, and invocable methods all run in system context unless your code adds the checks.
Deciding what to enforce
Use these questions when you review a class.
- Who is the caller, and should they see only their records? If yes, use
with sharing. - Should they be limited to the objects and fields their permissions allow? If yes, add user mode or an equivalent check.
- Does the code need to read data the user cannot normally see, such as a roll-up across all accounts? Isolate that logic in a small, documented
without sharingclass, and return only what the user is entitled to receive.
Exercise
A user's profile has no read access to Contact.Email. A with sharing class runs SELECT Id, Email FROM Contact with no other clauses. Does the query fail, and what changes if you add WITH USER_MODE?
Show answer
The query does not fail. The with sharing keyword applies only record-level sharing, so the user receives Email values for the contacts they can see. Object permissions and field-level security are not checked. With WITH USER_MODE, the query enforces field-level security as well, so it throws a System.QueryException because the user cannot read Email.
Exercise
A developer sees an error about an inaccessible field and changes the class from with sharing to without sharing to fix it. Why is this the wrong fix?
Show answer
Sharing keywords control record-level access only. A field error comes from field-level security, usually through user mode or WITH SECURITY_ENFORCED. Switching to without sharing does not change field permissions, and it widens the set of records the code can read. The right fix is to grant the field permission through a permission set, or to change the code so it does not require that field.