Sub topic 1
Why Apex Ignores User Permissions by Default
Prerequisites
This chapter assumes you already know the following:
- Basic Apex syntax, including classes, methods, and triggers.
- SOQL queries and DML statements (
insert,update,delete). - Salesforce profiles and permission sets, and how they grant access.
- The idea of object permissions (create, read, edit, delete, often shortened to CRUD) and field-level security (FLS).
- Basic Apex unit testing with
@IsTest.
You do not need to know anything about user mode yet. This chapter explains the problem that user mode solves. Later chapters show how to apply it.
What you will learn
By the end of this chapter you will be able to:
- Explain what system mode means for Apex and why it is the default.
- Describe what the
with sharingkeyword enforces, and what it leaves alone. - Recognize code that leaks data because it assumes the platform checks permissions for you.
- Name the ways a class gets its execution context.
Apex runs in system mode
When a user clicks a button, opens a page, or calls an API, the platform checks what that user is allowed to do. A profile may deny access to the Account object. A permission set may hide the AnnualRevenue field. These rules are enforced by the platform for standard UI and API calls.
Apex code behaves differently. By default, Apex runs in system mode. System mode means the code runs with the privileges of the platform itself, not those of the person who started it. In system mode:
- Object permissions (CRUD) are not checked.
- Field-level security (FLS) is not checked.
- Sharing rules are not checked, unless the class declares sharing behavior (covered below).
Think of it as a trusted back office. The user submits a request at the front desk. The staff behind the desk can open any filing cabinet, whether or not the requester could.
Why the platform works this way
Apex is often used to implement business logic that needs wider access than the caller has. Some examples:
- A trigger that updates a parent record the user cannot edit, to keep a rollup field correct.
- A service that writes an audit record in an object no profile can touch directly.
- A scheduled job that has no meaningful "current user" at all.
If Apex always applied the caller's permissions, these patterns would break. So the platform makes system mode the default and leaves it to the developer to opt in to enforcement. The cost of this choice is that safety is not automatic.
A concrete leak
Consider this class. It exposes an @AuraEnabled method to Lightning components.
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, AnnualRevenue FROM Account LIMIT 50];
}
}Suppose a user's profile has no read access to AnnualRevenue. If the user opens the standard Account page, the field is hidden. If the user opens a custom component that calls getAccounts(), the query still returns AnnualRevenue, because the query runs in system mode. The component can display the value, or anyone who inspects the network response can read it.
The same applies to a user whose profile has no read access to Account at all. The query returns rows anyway, filtered only by sharing.
The class above says with sharing, which many developers read as "this class respects the user's permissions." That reading is wrong, and the next sections explain why.
What `with sharing` does and does not do
Sharing and permissions are two separate layers of the Salesforce security model.
| Layer | Question it answers | Controlled by |
|---|---|---|
| Object permissions (CRUD) | Can this user create, read, edit, or delete records of this object? | Profiles, permission sets |
| Field-level security (FLS) | Can this user see or edit this field? | Profiles, permission sets |
| Sharing | Which individual records of the object can this user see or edit? | Org-wide defaults, role hierarchy, sharing rules, manual shares, teams |
The keywords with sharing, without sharing, and inherited sharing control only the third layer. They decide whether Apex applies record-level sharing rules during queries and DML.
A class declared with sharing:
- Filters query results to the records the running user can see.
- Blocks DML on records the running user cannot edit, because of record access.
It does not:
- Check whether the user can read the object at all.
- Hide fields the user cannot read.
- Prevent writes to fields the user cannot edit.
- Prevent creating or deleting records when the user lacks those object permissions.
So a user without Account read access, running a with sharing class, can still get Account rows back. Sharing narrows the set of rows. It does not decide whether the object or its fields are accessible.
The three sharing keywords
| Keyword | Record-level sharing behavior |
|---|---|
| `with sharing` | Enforces the running user's sharing rules. |
| `without sharing` | Ignores sharing rules and sees all records. |
| `inherited sharing` | Uses the sharing mode of the class that called it. If it is the entry point, it behaves as `with sharing`. |
If a class declares no sharing keyword, the behavior depends on how it is called. In most cases it runs with the sharing mode of its caller, but an entry point with no keyword runs without enforcing sharing. For this reason, declare a keyword explicitly on every class. with sharing is a sensible default for classes that touch user data.
Where system mode applies
System mode is the default for most Apex entry points, including:
- Triggers.
@AuraEnabledand@InvocableMethodmethods.- Apex REST and SOAP web services.
- Batch, Queueable, and Schedulable classes.
- Visualforce controllers and extensions.
- Anonymous Apex run from the Developer Console.
The details differ slightly between entry points. For example, an Apex REST service runs as the authenticated user for sharing purposes, but still ignores that user's CRUD and FLS. The common point is that the platform does not enforce CRUD and FLS for you in any of them.
One exception worth noting: Visualforce pages that bind directly to standard controllers, and standard Lightning pages, have the platform enforce CRUD and FLS on their own fields. That protection belongs to the standard components and does not carry over to Apex you write.
Why this matters for security
Missing permission checks are one of the most common findings in Salesforce security reviews. The typical failure has three parts:
- A developer writes an Apex method that is reachable from the client (Lightning, Experience Cloud, a public API).
- The method queries or modifies data without enforcing CRUD and FLS.
- A user with limited access calls the method directly, or modifies the client request, and receives or changes data they should not.
The risk is greatest in Experience Cloud sites and guest user scenarios, where many users have deliberately narrow permissions. It also applies inside a company. A sales representative who cannot see salary fields on the Employee object should not be able to read them through a helper method written for a different purpose.
Note that the hidden field does not need to be displayed by your component. If the field is in the query, it is in the response payload.
A write example
The same problem exists for DML. Consider this method:
public with sharing class ContactController {
@AuraEnabled
public static void updateEmail(Id contactId, String newEmail) {
Contact c = new Contact(Id = contactId, Email = newEmail);
update c;
}
}If the user can see the contact through sharing but has read-only FLS on Email, this method updates the field anyway. The sharing check passes because the record is accessible. No FLS check happens, because the DML runs in system mode.
The ways to close the gap
Apex offers several techniques to bring the user's permissions back into the picture. This tutorial focuses on the newest and most complete one, user mode, and compares it with the older ones later.
| Technique | Introduced idea |
|---|---|
| User mode (`WITH USER_MODE`, `as user`, `AccessLevel.USER_MODE`) | Run a single operation with the user's CRUD, FLS, and sharing. |
| `WITH SECURITY_ENFORCED` | Throw an error if a queried field or object is not accessible. Applies to SOQL only. |
| `Security.stripInaccessible` | Remove inaccessible fields from records instead of failing. |
| Schema describe checks | Manually test each field with calls such as `isAccessible()`. |
The following chapters walk through user mode first, because it replaces most uses of the others. A short preview shows the idea. Adding one clause to the leaking query changes its behavior:
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, AnnualRevenue FROM Account WITH USER_MODE LIMIT 50];
}
}With WITH USER_MODE, the query is checked against the running user's object permissions, FLS, and sharing. If the user cannot read AnnualRevenue, the query throws an exception instead of returning the value. How to handle that exception is covered in a later chapter.
Common mistakes
- Treating
with sharingas a full security check. It only handles record visibility. CRUD and FLS remain unenforced. - Assuming the UI hides what the code returns. The UI hides fields only because it chooses not to render them. The data is still sent to the browser.
- Relying on a page or component to restrict access. A user can call an
@AuraEnabledmethod directly, so the check must be in Apex. - Leaving out the sharing keyword. Without one, the sharing behavior depends on the caller, which makes it harder to reason about.
- Testing only as an administrator. Tests and manual checks run by an admin pass because admins have broad access. A leak only appears when a restricted user runs the code.
Summary
- Apex runs in system mode by default. It ignores the running user's CRUD and FLS.
with sharingcontrols record-level visibility only. It does not check object access or field access.- Any method reachable from a client can leak or change data if you do not enforce permissions in Apex.
- User mode is the current way to enforce CRUD, FLS, and sharing on a per-operation basis. The next chapters build on this.
Exercise
A class is declared public with sharing class ReportService. Its method runs SELECT Id, Salary__c FROM Employee__c. The running user has read access to the Employee__c object and to some employee records through sharing, but field-level security hides Salary__c from them. What does the query return, and why?
Show answer
It returns the employee records the user can see through sharing, and each record includes the Salary__c value. with sharing only filters records by sharing rules. It does not check field-level security, and the query runs in system mode, so the hidden field is still returned. Adding WITH USER_MODE to the query would make it fail with an exception instead.
Exercise
Name the three security layers a Salesforce user passes through, and say which of them the with sharing keyword affects.
Show answer
The layers are object permissions (CRUD), field-level security (FLS), and record-level sharing. The with sharing keyword affects only record-level sharing.
Exercise
A teammate says, "Our @AuraEnabled method is safe because the component never shows the Salary field." Give one reason this argument is wrong.
Show answer
The method returns the field in its response whenever it is in the query. The user can read the response in the browser's network tools, or call the method directly with their own code. Hiding a field in the component does not restrict access to it. The check has to happen in Apex.