Sub topic 9
Securing data for guest and external users
This chapter assumes you can already build a Lightning web component, write a basic Apex method with SOQL, and read profiles, permission sets, and sharing settings in Setup. It also assumes you have exposed a component in Experience Builder, which earlier chapters covered. Here you learn why the CaseList component from the earlier examples is only safe if the surrounding security settings are right.
Two kinds of site visitor
Experience Cloud sites serve two groups of people, and Salesforce secures them differently.
- Guest users are unauthenticated visitors. Every site has one guest user record, and all anonymous visitors share it. Its access comes from a guest user profile.
- External users log in with a Customer Community, Partner Community, or similar license. Each is a real user record linked to a contact, with a profile, permission sets, and record access based on their account and contact.
A component does not choose which group it serves. The same CaseList renders for both. What differs is what the platform allows the running user to read.
The security layers
Data reaches the browser only after several independent checks. A failure at any layer should stop the data.
Each layer is configured in a different place:
| Layer | Where you configure it | Guest user | External user |
|---|---|---|---|
| Apex class access | Profile or permission set | Guest user profile only | Profile or permission set |
| Object and field permissions | Profile or permission set | Guest user profile only | Profile or permission set |
| Record access | Sharing settings, rules, sharing sets, share groups | Guest user sharing rules | Sharing sets, share groups, roles, and sharing rules |
Client-side checks are only a convenience
The isGuest import in the example component decides whether to show a login prompt:
import isGuest from '@salesforce/user/isGuest';This keeps the page tidy, but it is not security. Anyone can open the browser console, call the Apex method through the Lightning runtime, or change maxRows to any value they like. Your Apex code and the platform's permissions must enforce the real rules. Treat every argument that comes from JavaScript as untrusted input.
Enforcing access in Apex
The sample controller uses two protections.
with sharingmakes the class respect record-level sharing for the running user.WITH USER_MODEmakes the query respect object permissions, field-level security, and sharing for that user.
Use with sharing on every controller that site components call. A without sharing class returns records regardless of the visitor's access. If you must use it, keep the unrestricted code in a small method and add explicit checks.
The sample query also has a weakness: LIMIT :maxRows accepts whatever number the client sends. A visitor could pass null, a negative number, or 50000. This version validates the input and refuses guests directly:
public with sharing class CaseListController {
private static final Integer DEFAULT_ROWS = 5;
private static final Integer MAX_ROWS = 50;
@AuraEnabled(cacheable=true)
public static List<Case> getMyCases(Integer maxRows) {
if (UserInfo.getUserType() == 'Guest') {
throw new AuraHandledException('Log in to see your cases.');
}
Integer rowLimit = DEFAULT_ROWS;
if (maxRows != null && maxRows > 0) {
rowLimit = Math.min(maxRows, MAX_ROWS);
}
return [
SELECT Id, CaseNumber, Subject, Status
FROM Case
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :rowLimit
];
}
}The guest check here is a second line of defense. Even if the guest profile were misconfigured later, this method would still refuse to return cases.
Securing the guest user profile
Salesforce locks down guest access by default, and the restrictions are strict:
- The guest user can only receive read access to objects. Create, edit, and delete permissions on the guest profile are limited, and the guest cannot be granted View All or Modify All.
- Record access for guests comes from guest user sharing rules. These are criteria-based and read-only. You cannot share records with the guest user through ownership or role hierarchy.
- The Secure guest user record access setting is on by default and cannot be switched off. Records the guest creates are owned by a default record owner you choose, not by the guest.
To work with the guest profile, open Experience Builder, go to Settings > General, and open the guest user profile link. Then follow these steps.
- In Enabled Apex Class Access, add only the classes your public components call.
- In Object Settings, grant read access only to objects that must be public. Then grant read access only to the fields the visitor needs.
- In Setup, create a guest user sharing rule only when the public must see specific records. Write the criteria as narrowly as possible, such as
Public__c = true.
For the CaseList component, a guest has no cases to see, so grant no Case access to the guest profile. The component then shows the login prompt, and the Apex guard from the previous section enforces it.
Securing data for external users
External users have a real profile, so you control them with profiles and permission sets. The harder part is record access. Their default access is set by the external organization-wide default for each object. A typical choice is Private, so users see only their own records. Then you open access in specific ways:
- Sharing sets grant access to records linked to the user's account or contact. For example, a customer sees cases whose account matches their own.
- Share groups let users in the same account share records with each other.
- Sharing rules and role-based access cover partner and internal-user scenarios.
With with sharing and WITH USER_MODE, the getMyCases query returns exactly the cases these rules allow, without a WHERE clause that tries to rebuild the same logic by hand. Hand-written filters such as WHERE ContactId = :userContactId are easy to get wrong and duplicate the platform's job.
Choosing between enforcement options
You have several ways to enforce user access in Apex. They differ in what they do on failure.
| Approach | Behavior when the user lacks access |
|---|---|
| `WITH USER_MODE` in SOQL | Throws an exception if a field or object is inaccessible |
| `WITH SECURITY_ENFORCED` | Throws an exception, but checks only fields and objects, not as completely as user mode |
| `Security.stripInaccessible` | Removes inaccessible fields from results and does not throw |
Use WITH USER_MODE as the default. Use stripInaccessible when you prefer partial results to an error, such as a component that can still render when one optional field is hidden.
Common mistakes
- Testing only as an admin. An administrator can see everything, so a broken permission setup goes unnoticed. Test as a real external user and as an unauthenticated visitor in a private browser window.
- Forgetting class access. If the profile lacks access to the Apex class, the wire adapter returns an error. A guest or external user sees an empty component with a permission error in the console.
- Caching sensitive data. Methods marked
cacheable=truecan be cached on the client. Do not use caching for data that is user-specific if the cached result could be shown to the wrong user after a login change. Reload the page on login and logout. - Trusting
isGuestfor access control. It only controls what the template shows. - Overusing
without sharing. It removes the record-level check for every caller, including guests.
Exercise
A teammate adds without sharing to CaseListController so that guests "see something" on the page. Name two checks that now no longer protect the data, and describe how you would fix the original problem.
Show answer
without sharing removes record-level sharing, so the guest sharing rules no longer limit which cases are returned. If the teammate also removes WITH USER_MODE, object and field permissions stop applying too. The fix is to restore with sharing and WITH USER_MODE, then decide whether guests should see any cases at all. If they should see some, create a narrow guest user sharing rule and grant read access to only the needed object and fields on the guest profile. If not, keep the login prompt.
Exercise
Why does the improved getMyCases method cap maxRows at 50 and fall back to 5, even though the page editor already limits the property?
Show answer
The value comes from JavaScript in the browser, so a visitor can call the Apex method with any number, including null or a very large one. Validating it in Apex stops oversized queries and unexpected behavior, because client input is never trusted.