Sub topic 11
Enforcing sharing and field-level security
This chapter assumes you can write basic Apex and SOQL, and that you have already built a component that wires getContacts to a property. Here you will look at what the Apex behind a wire must do to respect the running user's access.
Why the wire does not protect you
@wire only delivers whatever your Apex method returns. The platform does not filter the result for the current user. If the method returns a field the user cannot read, that field reaches the browser.
Apex runs in system context by default. It ignores the user's object permissions, field permissions, and record sharing. You have to opt in to each kind of enforcement.
| Layer | What it controls | How you enforce it in Apex |
|---|---|---|
| Record sharing | Which rows the user can see | `with sharing` on the class |
| Object permissions | Whether the user can read the object at all | `WITH USER_MODE` on the query |
| Field-level security | Which fields the user can read | `WITH USER_MODE` on the query |
Sharing: `with sharing`
The with sharing keyword makes the class respect sharing rules, role hierarchy, and manual shares. Without it, a query returns rows the user should not see.
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
];
}
}with sharing covers records only. It says nothing about objects or fields.
Object and field permissions: `WITH USER_MODE`
WITH USER_MODE runs the query with the user's object permissions and field-level security. It also applies sharing rules. If the user cannot read Email, the query throws a QueryException instead of quietly returning the value.
Older code often uses WITH SECURITY_ENFORCED. It checks only fields in the SELECT clause. WITH USER_MODE is the more complete choice, since it also checks fields in WHERE and ORDER BY, and it enforces sharing on its own. Use it in new code.
What happens in the component
When the user lacks access to a field, the query fails. The wire then delivers an error value rather than data. Your template already handles this if it checks contacts.error.
<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:elseif={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>The server error message is in error.body.message. It can name fields and objects, so decide whether to show it to users or only log it.
Common mistakes
- Omitting a sharing keyword. A class with no keyword inherits the sharing mode of its caller. When the platform invokes it directly from a component, it runs without sharing enforcement in many cases. State
with sharingexplicitly. - Assuming
cacheable=trueadds security. It only allows client-side caching. - Returning more fields than the component shows. Select only what you render, so you expose less if permissions change.
- Testing only as an administrator. Administrators usually have access to everything, so failures never appear.
Testing as a restricted user
Test your Apex with System.runAs using a user whose profile lacks the permission you are checking. Assert that the query throws.
@IsTest
private class ContactControllerTest {
@IsTest
static void blocksUserWithoutContactAccess() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'noacc',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'NoAccess',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'noaccess' + System.currentTimeMillis() + '@example.com'
);
Boolean blocked = false;
System.runAs(u) {
try {
ContactController.getContacts(null);
} catch (QueryException e) {
blocked = true;
}
}
System.assert(blocked, 'Expected a QueryException for a user without Contact access');
}
}Exercise
A wired Apex method uses with sharing on the class but its SOQL has no WITH USER_MODE. A user can see an account's contacts through sharing but has no read access to the Email field. What happens to Email, and how do you fix it?
Show answer
The query returns Email anyway, because with sharing only filters records and does not check field-level security. Add WITH USER_MODE to the query. The query then throws a QueryException, and the wire delivers it as error. Alternatively, remove Email from the SELECT list if the component does not need it.