By default Apex code executes without checking permissions. Hence the code will not enforce field level security, sharing rules and user
permissions during execution of Apex code in Triggers, Classes and Controllers. This creates the risk that unauthorized users may get access to
sensitive data records or fields.
To prevent this, developers should use with sharing
keyword when declaring their classes if the class has SOQL or SOSL queries or DML
Statements. This will ensure that current user’s permissions, field level security and sharing rules are enforced during code execution. Thus users
will only see or modify records and fields which they have access to.
Use without sharing
when a specific class should have full access to records without taking into account current user’s permissions.
This should be used very carefully.
Use inherited sharing
when the code should inherit the level of access from the calling class. This is more secure than not specifying
a sharing level as the default will be equivalent to "with sharing".
This rule raises an issue when a class containing DML, SOSL or SOQL queries has no sharing level specified (with sharing
,
without sharing
, inherited sharing
).
Noncompliant code example
public class MyClass { // Noncompliant, no sharing specified
List<Case> lstCases = new List<Case>();
for(Case c:[SELECT Id FROM Case WHERE Status = 'In Progress']){ // SOQL query
// ...
}
}
public class MyClass { // Noncompliant
List<List<SObject>> sList = [FIND 'TEST' IN ALL FIELDS
RETURNING Case(Name), Contact(FirstName,LastName)]; // SOSL query
}
public class MyClass { // Noncompliant
List<Case> lstCases = new List<Case>();
for(Case c:[SELECT Id, Status FROM Case WHERE Status = 'In Progress']){
c.Status = 'Closed';
lstCasesToBeUpdated.add(c);
}
Update lstCasesToBeUpdated; // DML query
}
Compliant solution
public with sharing class MyClass {
List<Case> lstCases = new List<Case>();
for(Case c:[SELECT Id FROM Case WHERE Status = 'In Progress']){
// ...
}
}
public without sharing class MyClass {
List<List<SObject>> sList = [FIND 'TEST' IN ALL FIELDS
RETURNING Case(Name), Contact(FirstName,LastName)];
}
public inherited sharing class MyClass {
List<Case> lstCases = new List<Case>();
for(Case c:[SELECT Id, Status FROM Case WHERE Status = 'In Progress']){
c.Status = 'Closed';
lstCasesToBeUpdated.add(c);
}
Update lstCasesToBeUpdated;
}
Exceptions
No issue will be raised for test classes, i.e. classes annotated with @isTest