Sub topic 12
Enforcing sharing and field-level security
This chapter covers how an Apex controller called from a Lightning Web Component (LWC) enforces record sharing and field-level security. It assumes you can write basic Apex and SOQL, and that you already know how to expose a method with @AuraEnabled and call it from a component.
Why the controller must enforce security
Apex runs in system context by default. It ignores the running user's object permissions, field permissions, and record sharing unless you ask it to apply them. An @AuraEnabled method is reachable by any user who can load the component. A user can also call the method from the browser console. If the controller does not enforce security, a user can read or change data they should not see.
Hiding a field in the template does not protect it. The data has already reached the browser by then. Enforcement has to happen in Apex.
Three separate layers apply here:
| Layer | Question it answers | How Apex enforces it |
|---|---|---|
| Object permissions (CRUD) | Can this user read, create, edit, or delete this object? | `WITH USER_MODE`, `as user`, or `Schema.DescribeSObjectResult` checks |
| Field-level security (FLS) | Can this user see or edit this field? | `WITH USER_MODE`, `as user`, or `stripInaccessible` |
| Record sharing | Can this user access this particular record? | `with sharing` on the class, or `WITH USER_MODE` on the query |
Sharing: `with sharing`
The sharing keyword on a class controls whether record-level sharing rules apply. It does not control CRUD or FLS.
with sharingapplies the running user's sharing rules.without sharingignores them.inherited sharinguses the sharing mode of the calling class. When it is the entry point, it behaves likewith sharing.- If you omit the keyword, the class runs in the mode of its caller. As an entry point, such as an
@AuraEnabledmethod, that is not the safe default you want. State the mode explicitly.
Declare with sharing on every controller class that LWC calls. Use without sharing only for a narrow, documented reason, and keep that code in a small separate class.
Object and field permissions: user mode
User mode is the simplest way to enforce all three layers on database operations. It applies the running user's object permissions, field permissions, and sharing rules.
The controller from the earlier chapters uses it in two places:
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> searchContacts(String searchTerm) {
String key = '%' + searchTerm + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE :key
WITH USER_MODE
ORDER BY Name
LIMIT 20
];
}
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
try {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (DmlException e) {
throw new AuraHandledException(e.getDmlMessage(0));
}
}
}In the query, WITH USER_MODE makes the platform check read access on Contact and on each selected or filtered field. If the user lacks access to Email, the query throws a QueryException instead of returning the field. In the update, update as user checks that the user can edit Contact and the Email field. If not, it throws a DmlException.
Both forms are available for other statements too:
Database.query(queryString, AccessLevel.USER_MODE)for dynamic SOQL.Database.insert(records, AccessLevel.USER_MODE)and the matching update, upsert, and delete methods.insert as user,update as user,upsert as user, anddelete as useras statement forms.
What user mode does not do
- It fails the whole operation on the first violation. It does not silently drop fields.
WITH USER_MODEandWITH SECURITY_ENFORCEDshould not be combined in one query. PreferUSER_MODE, which also applies sharing and checks fields inWHEREandORDER BY.- It does not apply to code outside the statement. If you read a field from a related object through a relationship path, that field is checked too, but data you assemble from other sources is not.
Silent filtering: `stripInaccessible`
Sometimes failing is the wrong behavior. A page may need to show whatever the user is allowed to see. Security.stripInaccessible removes inaccessible fields from records and reports what it removed.
public with sharing class ContactReadController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts() {
List<Contact> rows = [
SELECT Id, Name, Email, Phone
FROM Contact
LIMIT 50
];
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.READABLE,
rows
);
return (List<Contact>) decision.getRecords();
}
}This query runs in system mode for field access, and stripInaccessible removes the fields the user cannot read. The class is still with sharing, so record sharing applies. The component receives records without Email or Phone if the user lacks access, and it must handle the missing values. The method decision.getRemovedFields() returns a map of what was removed, which is useful for logging.
Use AccessType.CREATABLE or AccessType.UPDATABLE before DML to strip fields the user cannot write. AccessType.UPSERTABLE combines both.
Choosing between failing and filtering
| Behavior you want | Use |
|---|---|
| Reject the request when access is missing | `WITH USER_MODE`, `as user` |
| Return a partial record with only permitted fields | `Security.stripInaccessible` |
| Run privileged logic on purpose (for example, a roll-up the user may not read directly) | System mode in a small, reviewed class |
Keeping the security decision visible
Apply the rules in one place so a reviewer can verify them quickly.
- Put
with sharingon the controller class. - Use user mode on every query and DML statement in methods that LWC can call.
- Do not accept a field list or object name from the component and build SOQL from it. If you must build dynamic SOQL, bind variables or use
String.escapeSingleQuotes, and still run it in user mode. - Return only the fields the component renders. Smaller results leak less and run faster.
Injection through parameters
The searchTerm in the example is bound with :key. Binding keeps the value from changing the query structure. If you concatenate user input into a SOQL string, a caller can inject clauses. User mode limits the damage, because the injected query still runs with the user's permissions, but it does not prevent the injection itself.
Testing the security behavior
Apex tests run in system mode by default, so a passing test does not show that security works. Use System.runAs with a user whose profile or permission set lacks access:
@IsTest
private class ContactControllerTest {
@IsTest
static void searchFailsWithoutContactAccess() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'nouser',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'NoAccess',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'nouser' + DateTime.now().getTime() + '@example.com'
);
insert u;
Boolean threw = false;
System.runAs(u) {
try {
ContactController.searchContacts('a');
} catch (QueryException e) {
threw = true;
}
}
System.assert(threw, 'Expected a QueryException for a user without Contact access');
}
}Test both sides: one user with access, and one without. The Jest tests from the previous chapter mock the server, so they cannot verify any of this.
Surfacing security errors in the component
A security failure arrives in the component as a rejected Promise. User mode throws a QueryException or DmlException. The raw message can name fields and objects, which may be more detail than you want to show. Catch the exception in Apex and throw an AuraHandledException with a controlled message, as updateEmail does for DML. For queries, wrap the call the same way:
try {
return [SELECT Id, Name FROM Contact WHERE Name LIKE :key WITH USER_MODE LIMIT 20];
} catch (QueryException e) {
throw new AuraHandledException('You do not have access to search contacts.');
}The component then displays error.body.message, as in the earlier error-handling chapter.
Common mistakes
- Marking a class
without sharingto "fix" a missing-record error, which hides a sharing problem and exposes every record. - Relying on the template or on component-level checks to hide fields.
- Assuming
with sharingalso enforces field-level security. It enforces only record sharing. - Testing only as an administrator, who has access to everything.
- Using
cacheable=truemethods that return data one user may see and another may not. The client cache is per user, but the pattern is easy to misuse in shared UI code, so keep the security checks in the method anyway.
Exercise
A controller class is declared with sharing and runs [SELECT Id, Name, Salary__c FROM Employee__c] without any other security clause. The user has no read access to Salary__c. Does the component receive the salary, and how do you fix it?
Show answer
Yes, it receives the value. with sharing applies only record sharing, and a standard query ignores field-level security. Add WITH USER_MODE to the query so it throws a QueryException when the user lacks access to Salary__c. If you want to return the other fields instead, query normally and pass the results through Security.stripInaccessible(AccessType.READABLE, rows).
Exercise
Why can an Apex test that calls ContactController.searchContacts fail to prove that field-level security works, and what do you add to make it meaningful?
Show answer
Tests run in system mode and the test user usually has full access, so no violation occurs. Use System.runAs with a user whose profile or permission set lacks access to Contact or to the queried fields, and assert that the expected exception is thrown.