Incorrect sharing clauses
Why is this an issue?
Apex code runs in system context by default, bypassing object permissions, field-level security, and sharing rules. Classes without an explicit sharing declaration, or those using without sharing, may inadvertently expose data to users who should not have access.
This is particularly dangerous in:
Lightning components and Aura controllers
Visualforce controllers
REST/SOAP web services
Any code that handles user-supplied record IDs
Examples
Example of incorrect code:
public class AccountController {
// No sharing declaration - runs in system context
@AuraEnabled
public static List<Account> getAccounts() {
return [SELECT Id, Name, Revenue__c FROM Account];
}
}
public without sharing class AccountController {
// Explicitly bypasses sharing rules
}
Example of correct code:
public with sharing class AccountController {
@AuraEnabled
public static List<Account> getAccounts() {
return [SELECT Id, Name, Revenue__c FROM Account];
}
}
How can I fix violations?
An autofix exists for this rule.
Add
with sharing: Use thewith sharingkeyword to enforce the current user's sharing rules.Use
inherited sharing: For utility classes that should respect the calling context's sharing mode.Review
without sharingusage: Ifwithout sharingis required, document why and ensure it's not exposed to user-facing code.
When should I disable this rule?
You may dismiss specific violations for:
Batch Apex classes that need system-level access to process all records
Trigger handlers where sharing is enforced at a higher level
Utility classes with
inherited sharingthat delegate to the caller's context
Resources
