Sub topic 6
Respecting sharing and field-level security
This chapter assumes you can write Apex classes and SOQL, know the difference between object permissions, field-level security (FLS), and record sharing, and have already built an @InvocableMethod with request and response types. It covers how to make an Agentforce action see only the data the running user is allowed to see, and how to report a denied access to the agent.
Why actions need explicit security
Apex runs in system context by default. It ignores the running user's object permissions and field-level security, and sharing rules apply only if the class declares with sharing. An agent makes this risky because the person typing a request can ask for anything. If your action returns data the user could never open in the Salesforce UI, the agent will read that data back to them.
Three layers of access apply to every query or DML statement:
| Layer | Question it answers | Enforced by default in Apex? |
|---|---|---|
| Sharing | Can this user see this record? | Only in a `with sharing` class |
| CRUD | Can this user read, create, edit, or delete this object? | No |
| FLS | Can this user read or edit this field? | No |
The action must enforce all three. The simplest way is user mode.
Who is the running user?
The running user is the identity that Apex executes as. For an employee-facing agent, this is normally the employee chatting with the agent. For a customer-facing service agent, it is the user the agent is configured to run as. Check the setup of your agent type in your org. Either way, that user's profile and permission sets decide what the action can touch.
Two consequences follow:
- The running user needs access to your Apex class through a permission set or profile. Without it, the action cannot be invoked.
- Test with the least-privileged user that will realistically use the agent. An admin account hides every problem in this chapter.
Declare `with sharing`
Start every action class with with sharing. This makes record-level sharing apply to any query that does not specify an access mode.
public with sharing class GetCaseDetailsAction {
// ...
}with sharing does not enforce CRUD or FLS. A user who cannot see the Priority field can still read it through a query in a with sharing class.
Use user mode for queries and DML
User mode runs a single operation with the running user's sharing rules, object permissions, and FLS. It is the recommended approach for new code. In user mode, the sharing rules apply even if the class is declared without sharing or has no sharing keyword.
For static SOQL, add WITH USER_MODE:
List<Case> cases = [
SELECT Id, CaseNumber, Subject
FROM Case
WHERE AccountId = :accountId
WITH USER_MODE
];For DML, add as user, or pass AccessLevel.USER_MODE to a Database method:
insert as user new Case(Subject = 'Follow-up', AccountId = accountId);
Database.SaveResult[] results = Database.update(
casesToUpdate,
false,
AccessLevel.USER_MODE
);For dynamic SOQL, pass the access level as the second argument. Bind variables are safer than string concatenation:
List<Case> cases = Database.queryWithBinds(
'SELECT Id, Subject FROM Case WHERE AccountId = :accountId',
new Map<String, Object>{ 'accountId' => accountId },
AccessLevel.USER_MODE
);The GetOpenCasesAction example earlier in this tutorial already uses WITH USER_MODE on its single query. This chapter explains why that clause is there and what to do when it fails.
What happens when access is missing
User mode behaves differently depending on which layer denies access:
- Sharing. Records the user cannot see are silently left out of the result. You get fewer rows and no error.
- Object permission (CRUD). The operation throws an exception.
- Field-level security. If the query names a field the user cannot read, it throws an exception. The same applies to DML on a field the user cannot edit.
A failed read in user mode throws a QueryException. A failed DML statement throws a DmlException. If you do not catch these, the agent receives a generic failure and cannot tell the user what went wrong. Catch them and return a clear message in the response.
The first behavior has a trap. An empty list can mean "no records exist" or "you cannot see them". Your response text should not claim that nothing exists when the user may simply lack access. Say "No open cases were found that you can access" instead of "This account has no cases".
A complete example that handles denied access
This action looks up one or more cases by Id. It queries once, uses user mode, catches an access failure, and returns one response per request in the original order.
public with sharing class GetCaseDetailsAction {
public class Request {
@InvocableVariable(
label='Case Id'
description='The Salesforce Id of the case to look up'
required=true
)
public Id caseId;
}
public class Response {
@InvocableVariable(
label='Case Details'
description='Case number, subject, and priority, or a message explaining why details are not available'
)
public String details;
@InvocableVariable(
label='Access Denied'
description='True when the user lacks permission to read the requested case data'
)
public Boolean accessDenied;
}
@InvocableMethod(
label='Get Case Details'
description='Returns the case number, subject, and priority for a case the user can access'
category='Service'
)
public static List<Response> getDetails(List<Request> requests) {
Set<Id> caseIds = new Set<Id>();
for (Request r : requests) {
if (r.caseId != null) {
caseIds.add(r.caseId);
}
}
Map<Id, Case> casesById = new Map<Id, Case>();
Boolean denied = false;
try {
casesById = new Map<Id, Case>([
SELECT Id, CaseNumber, Subject, Priority
FROM Case
WHERE Id IN :caseIds
WITH USER_MODE
]);
} catch (QueryException e) {
denied = true;
}
List<Response> responses = new List<Response>();
for (Request r : requests) {
Response res = new Response();
res.accessDenied = denied;
if (denied) {
res.details = 'You do not have permission to read the case fields needed for this request.';
} else if (r.caseId != null && casesById.containsKey(r.caseId)) {
Case c = casesById.get(r.caseId);
res.details = c.CaseNumber + ': ' + c.Subject + ' (Priority: ' + c.Priority + ')';
} else {
res.details = 'No case was found that you have access to.';
}
responses.add(res);
}
return responses;
}
}Two details matter here. The catch sits around the query only, so unrelated bugs still surface as real errors. The Boolean output gives the agent a structured signal in addition to the text.
The request path
The diagram shows where each layer acts when the agent calls an action.
Alternatives to user mode
User mode is not always available or suitable. These are the other tools you will meet in existing code.
| Approach | Behavior | Use it when |
|---|---|---|
| `WITH USER_MODE` / `as user` | Enforces sharing, CRUD, and FLS. Throws on violations. | The default for new actions |
| `WITH SECURITY_ENFORCED` | Enforces CRUD and FLS on SOQL only. Does not enforce DML or polymorphic field checks fully. | Maintaining older code |
| `Security.stripInaccessible` | Removes inaccessible fields from records instead of throwing. | You want partial results, or you need to sanitize records before DML or before returning them |
| `Schema` describe checks such as `isAccessible()` | Manual per-object and per-field checks. | Dynamic field lists, or custom messages per field |
stripInaccessible suits cases where a missing field should not fail the whole action. This example removes fields the user cannot read from records you already have:
List<Case> cases = [SELECT Id, Subject, Priority FROM Case LIMIT 10];
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.READABLE,
cases
);
List<Case> safeCases = (List<Case>) decision.getRecords();
Set<String> removed = decision.getRemovedFields().get('Case');This query runs in system context, so stripInaccessible is the only thing protecting the data. Do not rely on it unless you apply it to every record before using or returning it. Prefer user mode, and use stripInaccessible for the cases it handles better.
Common errors
- Using
without sharingto "fix" missing records. The user is not allowed to see those records. Fix the sharing model or permission set instead. - Testing only as an admin. System administrators usually have access to everything, so denied-access paths never run.
- Returning data from a system-context query. If you must use system mode for a step, such as writing an audit record, keep that step isolated and never return its data to the agent.
- Catching
Exceptionaround the whole method. This hides logic bugs. Catch the specific exception around the specific statement. - Putting sensitive fields in output text. Agents repeat what you return. Return only the fields the action's purpose needs.
- Forgetting Apex class access. If the running user's permission set does not include the class, the action fails before your code runs.
Testing security behavior
A unit test that runs as a restricted user proves the security works. Create a user with a minimal profile, assign only the permission sets you want, and call the action inside System.runAs. Check that restricted fields produce your access message instead of an unhandled exception. The test in the unit testing chapter covers the happy path. Add at least one test of the denied path for each action that reads sensitive fields.
Exercise
An action's class is declared with sharing, and its query selects Salary__c without WITH USER_MODE. The running user can see the record through sharing but has no field-level read access to Salary__c. What does the query return, and how do you fix it?
Show answer
The query returns the record with the Salary__c value included, because with sharing enforces only record-level sharing and does not check FLS. Add WITH USER_MODE to the query so it enforces FLS, wrap it in a try/catch for QueryException, and return a message the agent can explain. The alternative is to remove the field from the query if the action does not need it.
Exercise
A user-mode query inside your action returns an empty list. Name two possible causes, and explain how you would word the response text.
Show answer
Either no matching records exist, or records exist but sharing hides them from the running user. Sharing exclusions produce no error. The response text should say that no matching records were found that the user can access, instead of stating that none exist.