Sub topic 11
Enforcing sharing and field-level security
This chapter assumes you can write a cacheable Apex method, wire it to a Lightning Web Component, and read basic SOQL. It covers what you must do in the Apex class so that a wired call respects the running user's record access and field permissions.
Why the wire does not protect you
A wire adapter only delivers what your Apex method returns. The component has no say in which records or fields come back. If the Apex runs in system context, a user who cannot see a field in the UI can still receive it through the wire, and anyone who can open the browser developer tools can read it.
By default, Apex runs in system mode. It ignores the user's object permissions, field-level security (FLS), and, unless the class declares sharing, record sharing. Securing a wired method means changing that behavior explicitly.
Three separate controls apply:
| Control | What it decides | How you enforce it in Apex |
|---|---|---|
| Sharing rules | Which records the user can see | Declare the class `with sharing` |
| Object permissions | Whether the user can read the object at all | `WITH USER_MODE` or `Security.stripInaccessible` |
| Field-level security | Which fields the user can read | `WITH USER_MODE` or `Security.stripInaccessible` |
These controls are independent. Fixing one does not fix the others.
Sharing: the class declaration
The sharing keyword on the class controls record visibility.
with sharingenforces the user's sharing rules, such as organization-wide defaults, role hierarchy, and sharing rules.without sharingignores them.- If you omit the keyword, the class inherits sharing from the code that called it. When an LWC calls the class directly, the entry point runs without sharing enforcement, so omitting the keyword is unsafe here.
Declare with sharing on every class that has an @AuraEnabled method. The controller from the earlier chapters does this:
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}Note that with sharing alone does not enforce FLS. A class can be with sharing and still return a field the user is not allowed to read. That is the job of WITH USER_MODE.
Object and field permissions with WITH USER_MODE
WITH USER_MODE is a SOQL clause that runs the query with the running user's permissions. It enforces:
- Object read access.
- Field-level security on every field in the
SELECT,WHERE, andORDER BYclauses. - Sharing rules, even when the class is declared
without sharing.
If the user lacks access to something the query references, Apex throws a System.QueryException and returns nothing. The wire then delivers that failure as error.
Failing loudly versus filtering quietly
WITH USER_MODE is strict. If one field in the query is not readable, the whole query fails. That is often what you want, because it surfaces a misconfigured permission set during development. It can be a poor experience when users have different field access and you want to return whatever they are allowed to see.
For that case, use WITH SECURITY_ENFORCED or Security.stripInaccessible. Prefer stripInaccessible here, because it removes the fields instead of failing:
public with sharing class ContactFilteredController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
List<Contact> contacts = [
SELECT Id, Name, Email, Phone
FROM Contact
WHERE AccountId = :accountId
ORDER BY Name
LIMIT 50
];
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.READABLE,
contacts
);
return (List<Contact>) decision.getRecords();
}
}The query in this version runs in system mode for fields, because it has no WITH USER_MODE clause. Sharing still applies because of with sharing. stripInaccessible then removes any field the user cannot read before the records leave Apex. The component receives records where those fields are simply absent.
Choose between the two approaches like this:
| Situation | Better choice |
|---|---|
| You want a clear error when access is missing | `WITH USER_MODE` |
| Users have varying field access and partial data is acceptable | `Security.stripInaccessible` |
| You are writing new code on a current API version | `WITH USER_MODE` (it supersedes `WITH SECURITY_ENFORCED`) |
If you use stripInaccessible, the template must tolerate a missing field. contact.Email is undefined for a user without access, so the page should not assume it exists.
Dynamic SOQL and bind variables
If you build a query as a string, the same rules apply, and you also take on injection risk. Use Database.queryWithBinds with an access level, which enforces user mode and keeps values out of the query text:
public with sharing class ContactSearchController {
@AuraEnabled(cacheable=true)
public static List<Contact> search(String term) {
String pattern = '%' + String.escapeSingleQuotes(term) + '%';
return Database.queryWithBinds(
'SELECT Id, Name FROM Contact WHERE Name LIKE :pattern LIMIT 50',
new Map<String, Object>{ 'pattern' => pattern },
AccessLevel.USER_MODE
);
}
}The :pattern placeholder is a bind variable. Its value is never parsed as SOQL, so a user cannot change the structure of the query by typing special characters.
How caching interacts with security
Cacheable methods store their results on the client. The cache belongs to the browser session of one user, so one user's results are not served to another user. Security still depends on the Apex, for these reasons:
- The result is computed once under the permissions the user had at that moment. If an administrator changes the user's permissions during the session, the cached result can stay stale until it is refreshed or expires.
- Do not put secrets or per-request security decisions in a cacheable method. A cacheable method must not change data, and its output may be reused without running your code again.
- Never rely on the component to hide a field. Hiding a value in the template does not remove it from the response.
Testing the security behavior
Security rules are easy to break without noticing, because a developer usually runs as an administrator who can see everything. Test as a restricted user. In Apex, System.runAs runs a block as another user, and it enforces sharing and permissions for that block when the user and records are set up.
@IsTest
private class ContactControllerTest {
@IsTest
static void restrictedUserGetsAccessError() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'tstusr',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tstusr' + DateTime.now().getTime() + '@example.com'
);
insert u;
Account a = new Account(Name = 'Test');
insert a;
Boolean threw = false;
System.runAs(u) {
try {
ContactController.getContacts(a.Id);
} catch (QueryException e) {
threw = true;
}
}
System.assert(threw, 'A user without Contact access should get a QueryException');
}
}The profile name Minimum Access - Salesforce exists in most orgs but not all. Adjust it to a profile in your org that lacks Contact read access.
Common mistakes
- Omitting the sharing keyword. The class then runs without enforcing sharing when called from an LWC. Always declare
with sharing. - Assuming
with sharingcovers FLS. It covers record access only. AddWITH USER_MODEorstripInaccessible. - Swallowing the exception. If you catch
QueryExceptionand return an empty list, the user sees "no contacts" and cannot tell that a permission is missing. Let the exception propagate, or throw anAuraHandledExceptionwith a clear message. - Returning more fields than the component uses. Extra fields widen what a user can read from the response. Select only what the template needs.
- Testing only as an administrator. Use
System.runAswith a restricted user.
Throwing a readable error
Raw exception text may not suit users. Wrap it in an AuraHandledException so that error.body.message carries a controlled message:
public with sharing class ContactSafeController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
try {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
} catch (QueryException e) {
throw new AuraHandledException('You do not have access to these contact fields.');
}
}
}The wire delivers this as error, and the component reads error.body.message to show the text.
Exercise
A class is declared public with sharing and contains a cacheable @AuraEnabled method whose query has no WITH USER_MODE clause and does no stripInaccessible call. A user can see a Contact record through sharing but has no read access to the Contact Email field. Does the wired component receive Email, and why?
Show answer
Yes, it receives Email. with sharing enforces only record-level sharing, so the user's access to the record is respected. Field-level security is not enforced by the class keyword. Without WITH USER_MODE or Security.stripInaccessible, the query reads the field in system mode and returns it. Add WITH USER_MODE to fail the query, or call stripInaccessible to remove the field.
Exercise
Your team wants a wired list to show whatever fields each user is allowed to see, instead of failing for users who lack access to one field. Which approach fits, and what must the template handle?
Show answer
Use Security.stripInaccessible(AccessType.READABLE, records) in a with sharing class. It removes unreadable fields from the records instead of throwing. The template must handle fields that are undefined, because a stripped field is absent from the returned record.