Apex Security · Lesson 35 of 41
Apex Security: Sharing, CRUD, FLS and User Mode
Salesforce has a rich security model: profiles and permission sets decide which objects and fields a user can see, sharing decides which records. Here's the uncomfortable truth: by default, Apex ignores most of it. Code runs in system mode, so a careless controller can show a user salaries they shouldn't see or let them edit records they can't open in the UI. This lesson shows each layer, how to enforce it, and proves the behaviour with real tests.
In this lesson
- System mode vs user mode
- Record access: with, without and inherited sharing
- Object and field access: WITH USER_MODE and as user
- Security.stripInaccessible
- A security checklist
Three layers of access
- Object permissions (CRUD)can the user create, read, edit, delete Expenses at all? – profiles and permission sets
- Field-level security (FLS)can they see or edit the Approver Notes field?
- Record access (sharing)which Expense records? – org-wide defaults, role hierarchy, sharing rules, manual shares
| System mode (default) | User mode | |
|---|---|---|
| Object permissions | ignored | enforced |
| Field-level security | ignored | enforced |
| Sharing | decided by the class's sharing keyword | enforced |
The example setup
To see real differences we need an object whose records are private. This custom object has a Private sharing model, an Amount field, and an Approver Notes field that ordinary users shouldn't see. A permission set grants read/create/edit on the object and access to Amount only:
<?xml version="1.0" encoding="UTF-8"?>
<!-- objects/Expense__c/Expense__c.object-meta.xml -->
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Expense</label>
<pluralLabel>Expenses</pluralLabel>
<nameField><label>Expense Name</label><type>Text</type></nameField>
<deploymentStatus>Deployed</deploymentStatus>
<sharingModel>Private</sharingModel>
<externalSharingModel>Private</externalSharingModel>
</CustomObject>
<?xml version="1.0" encoding="UTF-8"?>
<!-- objects/Expense__c/fields/Amount__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Amount__c</fullName>
<label>Amount</label>
<type>Currency</type>
<precision>16</precision>
<scale>2</scale>
</CustomField>
<?xml version="1.0" encoding="UTF-8"?>
<!-- objects/Expense__c/fields/Approver_Notes__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Approver_Notes__c</fullName>
<label>Approver Notes</label>
<type>Text</type>
<length>255</length>
</CustomField>
<?xml version="1.0" encoding="UTF-8"?>
<!-- permissionsets/Expense_User.permissionset-meta.xml -->
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Expense User</label>
<objectPermissions>
<object>Expense__c</object>
<allowCreate>true</allowCreate>
<allowRead>true</allowRead>
<allowEdit>true</allowEdit>
<allowDelete>false</allowDelete>
<modifyAllRecords>false</modifyAllRecords>
<viewAllRecords>false</viewAllRecords>
</objectPermissions>
<fieldPermissions>
<field>Expense__c.Amount__c</field>
<readable>true</readable>
<editable>true</editable>
</fieldPermissions>
</PermissionSet>
Record access: sharing keywords
A class's sharing keyword decides whether its queries and DML respect record sharing:
// ExpenseQueries.cls
public with sharing class ExpenseQueries {
public static List<Expense__c> visibleToUser() {
return [SELECT Id, Name FROM Expense__c]; // only records the user can access
}
public static List<Expense__c> everything() {
return ExpenseAdminQueries.all(); // delegates to a without sharing class
}
}
// ExpenseAdminQueries.cls
public without sharing class ExpenseAdminQueries {
// deliberately ignores sharing – e.g. for a nightly total across all expenses
public static List<Expense__c> all() {
return [SELECT Id, Name FROM Expense__c];
}
}
| Keyword | Behaviour |
|---|---|
with sharing | enforces the running user's record access – make this your default |
without sharing | ignores sharing; use deliberately, in small, clearly named classes |
inherited sharing | takes the caller's mode; runs as with sharing when it's the entry point – ideal for utilities |
| (no keyword) | inherits from the caller, but runs without sharing as an entry point – always declare one |
Sharing keywords only control records. A with sharing class still ignores object and field permissions unless you also use user mode.
Object and field access: user mode
Add WITH USER_MODE to SOQL and as user to DML (or pass AccessLevel.USER_MODE to Database methods). The operation then enforces object permissions, FLS and sharing – and fails clearly if the user lacks access:
// ExpenseService.cls
public with sharing class ExpenseService {
public static List<Expense__c> myExpensesWithNotes() {
return [SELECT Name, Amount__c, Approver_Notes__c FROM Expense__c WITH USER_MODE];
}
public static List<Expense__c> myExpensesSafe() {
// strip what the user can't read instead of failing
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.READABLE, [SELECT Name, Amount__c, Approver_Notes__c FROM Expense__c]);
return (List<Expense__c>) decision.getRecords();
}
public static void deleteExpense(Id expenseId) {
delete as user new Expense__c(Id = expenseId);
}
}
Proving it with tests
Two users get the Expense User permission set. The owner creates an expense; the other user tries to see it. Every assertion below ran in a real org:
// ExpenseSecurityTest.cls
@IsTest
private class ExpenseSecurityTest {
static User newUser(String alias, String profileName) {
Profile p = [SELECT Id FROM Profile WHERE Name = :profileName];
return new User(Alias = alias, Email = alias + '@example.com', EmailEncodingKey = 'UTF-8', LastName = alias,
LanguageLocaleKey = 'en_US', LocaleSidKey = 'en_US', ProfileId = p.Id, TimeZoneSidKey = 'Asia/Kolkata',
Username = alias + System.now().getTime() + '@lf-example.com');
}
@TestSetup
static void makeData() {
User owner = newUser('ownr', 'Standard User');
User other = newUser('othr', 'Standard Platform User');
System.runAs(new User(Id = UserInfo.getUserId())) { // setup DML in its own context
insert new List<User>{ owner, other };
Id ps = [SELECT Id FROM PermissionSet WHERE Name = 'Expense_User'].Id;
insert new List<PermissionSetAssignment>{
new PermissionSetAssignment(AssigneeId = owner.Id, PermissionSetId = ps),
new PermissionSetAssignment(AssigneeId = other.Id, PermissionSetId = ps)
};
}
System.runAs(owner) {
insert new Expense__c(Name = 'Taxi to client', Amount__c = 450, Approver_Notes__c = 'check receipt');
}
}
static User userWithAlias(String alias) {
return [SELECT Id FROM User WHERE Alias = :alias LIMIT 1];
}
@IsTest
static void withSharingHidesOtherUsersRecords() {
System.runAs(userWithAlias('othr')) {
Assert.areEqual(0, ExpenseQueries.visibleToUser().size(), 'private record is hidden');
Assert.areEqual(1, ExpenseQueries.everything().size(), 'without sharing sees it anyway');
}
}
@IsTest
static void userModeEnforcesFieldSecurity() {
System.runAs(userWithAlias('ownr')) {
try {
ExpenseService.myExpensesWithNotes();
Assert.fail('expected a QueryException for the hidden field');
} catch (QueryException e) {
Assert.isTrue(e.getMessage().contains('Approver_Notes__c'), e.getMessage());
}
}
}
@IsTest
static void stripInaccessibleRemovesHiddenFields() {
System.runAs(userWithAlias('ownr')) {
List<Expense__c> rows = ExpenseService.myExpensesSafe();
Assert.areEqual(1, rows.size());
Assert.areEqual(450, rows[0].Amount__c);
Assert.isFalse(rows[0].isSet('Approver_Notes__c'), 'the hidden field was stripped');
}
}
@IsTest
static void asUserDmlEnforcesObjectPermissions() {
Id expenseId = [SELECT Id FROM Expense__c LIMIT 1].Id;
System.runAs(userWithAlias('ownr')) {
try {
ExpenseService.deleteExpense(expenseId);
Assert.fail('the permission set does not allow delete');
} catch (Exception e) {
Assert.isTrue(e.getMessage().containsIgnoreCase('delete') || e instanceof DmlException, e.getMessage());
}
}
Assert.areEqual(1, [SELECT COUNT() FROM Expense__c], 'record still exists');
}
}
✓ ExpenseSecurityTest.asUserDmlEnforcesObjectPermissions ✓ ExpenseSecurityTest.stripInaccessibleRemovesHiddenFields ✓ ExpenseSecurityTest.userModeEnforcesFieldSecurity ✓ ExpenseSecurityTest.withSharingHidesOtherUsersRecords Tests: 4 passed, 0 failed, 4 total
- Sharing: the other user's
with sharingquery found nothing; thewithout sharingclass found the record – exactly whywithout sharingmust be rare and deliberate. - FLS: the owner could create the record (system mode DML), but the user-mode query refused to read a field the permission set doesn't grant.
- stripInaccessible: instead of failing, it removed the hidden field and returned the rest – ideal for read-only views.
- CRUD:
delete as userwas refused because the permission set doesn't allow delete.
Older techniques you'll see
WITH SECURITY_ENFORCEDin SOQL – enforces object and field read access (not sharing).WITH USER_MODEreplaces it and also reports all inaccessible fields.- Manual checks:
Schema.SObjectType.Expense__c.isDeletable(),Schema.SObjectType.Expense__c.fields.Amount__c.isAccessible(). Still useful to hide a button before the user even tries.
Apex security checklist
- Declare
with sharing(orinherited sharing) on every class; isolatewithout sharing. - Use
WITH USER_MODE/as userin code that acts for a user – LWC controllers, REST resources, invocable actions. - Remember: any user with access to a class can call all its
@AuraEnabledmethods – grant class access via permission sets only to the right users. - Bind variables in SOQL; validate names in dynamic SOQL (dynamic SOQL).
- Keep secrets in Named Credentials, never in code or custom settings.
- Don't log sensitive data; don't return more fields than the UI needs.
Practice
Try it yourself
An LWC controller is
with sharingbut users can see a Salary field hidden by FLS. Why, and what's the fix?Show answer
Sharing keywords don't enforce FLS. Query with
WITH USER_MODE(or usestripInaccessible) so the hidden field is refused or removed.A utility class used by both a batch job and an LWC controller needs to respect the caller's sharing. Which keyword?
Show answer
inherited sharing– it runs in the caller's mode, and defaults to with sharing when called directly as an entry point.
Quick check
Does with sharing enforce field-level security?
No – only record access. Use user mode for CRUD and FLS.
What does WITH USER_MODE enforce?
Object permissions, field-level security and sharing.
What does stripInaccessible do?
Removes fields the user can't access from records instead of throwing an error.
Summary
- Apex runs in system mode by default – security is your job.
- Sharing keywords control record access; prefer with or inherited sharing.
- WITH USER_MODE and as user enforce CRUD, FLS and sharing.
- stripInaccessible returns safe data; test security with runAs users.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.