Skip to main content

Code reviews rule: Incorrect sharing clauses

Written by David Martin
Updated this week

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.

  1. Add with sharing: Use the with sharing keyword to enforce the current user's sharing rules.

  2. Use inherited sharing: For utility classes that should respect the calling context's sharing mode.

  3. Review without sharing usage: If without sharing is 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 sharing that delegate to the caller's context

Resources

Did this answer your question?