SlideShare a Scribd company logo
1 of 26
Field Level Security in Apex
Learn MOAR in Spring ’20
Rajesh Gupta
Senior Tech Lead
iBirds Software Services Pvt. Ltd., Ajmer
LinkedIn: https://www.linkedin.com/in/bitrajindia
Salesforce provides a comprehensive and flexible data security model to secure data at
different levels....
In Salesforce
Data is stored in three key constructions:
 Objects
 Fields
 Records
As a Admin, you can control WHO SEE WHAT using Sharing rules, field and object
permissions.
Salesforce uses
 Object-level : Profiles and Permission sets.
 Field-level : Profiles also control field-level access.
 Record-level security : OWD, Role, Sharing Rules, Manual Sharing
In Apex
public With Sharing class Sharingclass
{
//code
}
public Without Sharing class nonsharing
{
//code
}
With sharing keywords when declaring a class enforces Sharing Rules, but not object
and field-level permissions
 Using Schema Methods
 Using WITH SECURITY_ENFORCED clause
 Using stripInaccessible Method
There are some ways in which you can enforce object-level and field-level
permissions in Apex.
Check if the Email field on the Contact Object is accessible/readable by the logged in user.
if (Schema.sObjectType.Contact.fields.Email.isAccessible()) {
Contact c = [SELECT Email FROM Contact WHERE Id= :Id];
}
For example,
Imagine that you have a bunch of fields in your query, and you have inner
queries . This if statement becomes complex to maintain.
Drawback:
Using WITH SECURITY_ENFORCED clause
Starting Spring ‘20, the WITH SECURITY_ENFORCED clause can be
used in SOQL queries to enforce field and object level security
permissions in Apex code, including subqueries and cross-object
relationships.
Field-level permissions are checked for all the fields that are retrieved in
the SELECT clause(s) of the query. Since this clause only works inside
an SOQL query, it’s only useful when you want to check for read access
on a field
Using WITH SECURITY_ENFORCED clause
Example 1:
List<Account> act1 = [ SELECT Id, Name, (SELECT LastName FROM Contacts)
FROM Account WHERE Name like 'Acme'
WITH SECURITY_ENFORCED ];
The above query will return the Id and Name of Accounts, and the LastName of the related
contacts, only if the user has read access to all of these three fields. If the user doesn’t have
access to at least one of these fields, the query throws a System.QueryException exception,
and no results are returned. As a best practice, SOQL queries that use this clause, have to
be enclosed in a try/catch block, so that errors can be gracefully handled.
Using WITH SECURITY_ENFORCED clause
try{
List<Account> act1 = [ SELECT Id, Name, (SELECT LastName FROM Contacts)
FROM Account
WHERE Name like 'Acme'
WITH SECURITY_ENFORCED
];
}
catch(System.QueryException) {
//TODO: Handle Errors
}
Using WITH SECURITY_ENFORCED clause
Example 2:
List<Contact> contacts = [SELECT Id, Name, BirthDate
FROM Contact
WHERE Picture_URL__c != null WITH SECURITY_ENFORCED];
However, it is important to note that this clause doesn’t verify field-level
security for fields used in the WHERE clause of the query. For example, if a
user doesn’t have access a custom field called Picture_URL__c on the
Contact object, the below query doesn’t throw an error, and the results are
returned as usual.
Using stripInaccessible Method
The stripInaccessible method from the new Security class to enforce field and
object level security in Apex.
Like the name suggests, this method can be used to strip the fields from
sObject lists to which the user doesn’t have appropriate access, depending on
the operation being performed.
stripInaccessible(System.AccessType accessCheckType, List<sObject>
sourceRecords, [Boolean enforceRootObjectCRUD])
Using stripInaccessible Method
 accessCheckType: This parameter defines the type of field-level access check to be
performed. It accepts System.AccessType enum values: CREATABLE, READABLE,
UPDATABLE, UPSERTABLE.
 sourceRecords: A list of sObjects to be checked for fields that aren’t accessible in the
context of the current user’s operation.
 enforceRootObjectCRUD: An optional parameter that indicates whether object-level access
check has to be performed. If set to true, and the user doesn’t have the necessary CRUD
permissions on the object, this method throws an exception. It defaults to true.
Using stripInaccessible Method
This method returns an object of type SObjectAccessDecision. You use the
getRecords() method to access the list of sObjects which are stripped of
fields that fail the field-level security checks for the current user
For error handling purposes, you can use the getRemovedFields() method to
access a map of sObject types and their corresponding inaccessible fields.
Using stripInaccessible Method
Here is an example of a DML operation, where the current user doesn’t have access to a
custom field Picture_URL__c on the Contact Object:
List<Contact> contacts = new List<Contact>{
new Contact(FirstName='Jane', LastName='Doe', Picture_URL__c='someurl'),
new Contact(FirstName='John', LastName='Doe', Picture_URL__c='someurl'),
};
// Strip fields that are not creatable
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.CREATABLE,contacts);
//DML
try{
insert decision.getRecords();
}catch(NoAccessException e){
//TODO: Handle Error if the user lacks create permission on the Object
}
// OPTIONAL: Print removed fields
System.debug(decision.getRemovedFields());
Using stripInaccessible Method
The DML operation written above runs successfully without exceptions, but the Picture URL
field on the inserted records would be blank because the current user doesn’t have
appropriate permissions on it, therefore the value has been stripped off. However, if the user
lacked the create permission on the Contact object itself, the DML statement would throw an
exception.
Here is another example of the method’s usage in a query operation, where the current user
doesn’t have access to a custom field Picture_URL__c on the Contact Object.
Security.SObjectAccessDecision securityDecision =
Security.stripInaccessible(AccessType.READABLE,[SELECT Name, Picture_URL__c
FROM Contact ];);
for (Contact c : securityDecision.getRecords()) {
system.debug(c.Name); //Prints: Jane, John
system.debug(c.Picture_URL__c); //Prints: null, null
}
Inaccessible fields are removed from the query result, therefore those fields would return
a NULL value.
If you are using the stripInaccessible method on a list of sObject records that have already
been retrieved by a query, remember to use the getRecords() method to access the list of
records with inaccessible fields removed. The original list of records is not updated by the
stripInaccessible method and would still contain the values of inaccessible fields.
List<Contacts> contacts = [SELECT Name, Picture_URL__c from Contact];
Security.SObjectAccessDecision securityDecision =
Security.stripInaccessible(AccessType.READABLE, contacts);
system.debug(contacts); //Insecure access
system.debug(securityDecision.getRecords()); //Secure access
To sum up, this method can be used to:
 Strip fields from query results that the user doesn’t have read access to.
 Remove inaccessible fields before a DML operation without causing an exception.
 Sanitize sObjects that have been deserialized from an untrusted source.
Using stripInaccessible Method
Summary
These new techniques make the code less verbose and more efficient.
 The WITH SECURITY_ENFORCED clause can be used directly in an SOQL query to
check for read access on fields, and the query will throw an exception if a single field isn’t
accessible.
 stripInaccessible method can be used in read, create, update and upsert operations to strip
the fields from sObject Lists that are inaccessible.
Points To Remember -
 stripInaccessible method is a preview and isn’t part of the “Services” under your master
subscription agreement with Salesforce. This feature is for evaluation purposes only, not for
production use. It’s offered as is and isn’t supported, and Salesforce has no liability for any
harm or damage arising out of or in connection with it.
 The return list is identical to the source records, except that the fields that are inaccessible to
the current user are removed. the getRecords method contain records in the same order as
the sObjects in the sourceRecords parameter of the stripInaccessible method.
 The ID field is never stripped by the stripInaccessible method to avoid issues when
performing DML on the result.
Points To Remember -
 The ID field is never stripped by the stripInaccessible method to avoid issues when
performing DML on the result.
 The stripInaccessible method doesn’t support AggregateResult SObject. If the source records
are of AggregateResult SObject type, an exception is thrown.
Field Level Security  -  Spring 20

More Related Content

What's hot

Cognos Macros: Situational Examples & Syntax
Cognos Macros: Situational Examples & SyntaxCognos Macros: Situational Examples & Syntax
Cognos Macros: Situational Examples & SyntaxBryan L. Mack
 
Web security with Eng Ahmed Galal and Eng Ramy saeid
Web security with Eng Ahmed Galal and Eng Ramy saeid Web security with Eng Ahmed Galal and Eng Ramy saeid
Web security with Eng Ahmed Galal and Eng Ramy saeid Ahmed Ghazey
 
Defcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injectionDefcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injectionAhmed AbdelSatar
 
Ivanti Cheat Sheet by Traversys Limited
Ivanti Cheat Sheet by Traversys LimitedIvanti Cheat Sheet by Traversys Limited
Ivanti Cheat Sheet by Traversys LimitedTim Read
 
SQL Injection Attacks cs586
SQL Injection Attacks cs586SQL Injection Attacks cs586
SQL Injection Attacks cs586Stacy Watts
 

What's hot (8)

Cognos Macros: Situational Examples & Syntax
Cognos Macros: Situational Examples & SyntaxCognos Macros: Situational Examples & Syntax
Cognos Macros: Situational Examples & Syntax
 
Asp
AspAsp
Asp
 
Web security with Eng Ahmed Galal and Eng Ramy saeid
Web security with Eng Ahmed Galal and Eng Ramy saeid Web security with Eng Ahmed Galal and Eng Ramy saeid
Web security with Eng Ahmed Galal and Eng Ramy saeid
 
Defcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injectionDefcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injection
 
Ivanti Cheat Sheet by Traversys Limited
Ivanti Cheat Sheet by Traversys LimitedIvanti Cheat Sheet by Traversys Limited
Ivanti Cheat Sheet by Traversys Limited
 
XPath Injection
XPath InjectionXPath Injection
XPath Injection
 
SQL Injection Attacks cs586
SQL Injection Attacks cs586SQL Injection Attacks cs586
SQL Injection Attacks cs586
 
@Prompt
@Prompt@Prompt
@Prompt
 

Similar to Field Level Security - Spring 20

Appreciative Advanced Blind SQLI Attack
Appreciative Advanced Blind SQLI AttackAppreciative Advanced Blind SQLI Attack
Appreciative Advanced Blind SQLI Attackijtsrd
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Understanding advanced blind sqli attack
Understanding advanced blind sqli attackUnderstanding advanced blind sqli attack
Understanding advanced blind sqli attackNguyễn Đoàn
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaalifha12
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad NicheTech Com. Solutions Pvt. Ltd.
 
IRJET- A Review On - Controlchain: Access Control using Blockchain
IRJET- A Review On - Controlchain: Access Control using BlockchainIRJET- A Review On - Controlchain: Access Control using Blockchain
IRJET- A Review On - Controlchain: Access Control using BlockchainIRJET Journal
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPAli Shah
 
Migration of application schema to windows azure
Migration of application schema to windows azureMigration of application schema to windows azure
Migration of application schema to windows azureeSAT Publishing House
 
R Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioR Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioRobert Tanenbaum
 
OER Unit 4 Virtual Private Database
OER Unit 4 Virtual Private DatabaseOER Unit 4 Virtual Private Database
OER Unit 4 Virtual Private DatabaseGirija Muscut
 
Advanced Apex Security Expert Tips and Best Practices (1).pptx
Advanced Apex Security Expert Tips and Best Practices (1).pptxAdvanced Apex Security Expert Tips and Best Practices (1).pptx
Advanced Apex Security Expert Tips and Best Practices (1).pptxmohayyudin7826
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPTAjay Chimmani
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]Mohamed Abdeen
 
Database Security Methods, DAC, MAC,View
Database Security Methods, DAC, MAC,ViewDatabase Security Methods, DAC, MAC,View
Database Security Methods, DAC, MAC,ViewDr-Dipali Meher
 
Row-level security and Dynamic Data Masking
Row-level security and Dynamic Data MaskingRow-level security and Dynamic Data Masking
Row-level security and Dynamic Data MaskingSolidQ
 
Overview on SQL Injection Attacks
Overview on SQL Injection AttacksOverview on SQL Injection Attacks
Overview on SQL Injection Attacksijsrd.com
 
Wellrailed - Be9's Acl9
Wellrailed - Be9's Acl9Wellrailed - Be9's Acl9
Wellrailed - Be9's Acl9breccan
 

Similar to Field Level Security - Spring 20 (20)

Appreciative Advanced Blind SQLI Attack
Appreciative Advanced Blind SQLI AttackAppreciative Advanced Blind SQLI Attack
Appreciative Advanced Blind SQLI Attack
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Understanding advanced blind sqli attack
Understanding advanced blind sqli attackUnderstanding advanced blind sqli attack
Understanding advanced blind sqli attack
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
 
IRJET- A Review On - Controlchain: Access Control using Blockchain
IRJET- A Review On - Controlchain: Access Control using BlockchainIRJET- A Review On - Controlchain: Access Control using Blockchain
IRJET- A Review On - Controlchain: Access Control using Blockchain
 
Chapter23
Chapter23Chapter23
Chapter23
 
20.1 creating functions_part_20.1
20.1 creating functions_part_20.120.1 creating functions_part_20.1
20.1 creating functions_part_20.1
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 
Migration of application schema to windows azure
Migration of application schema to windows azureMigration of application schema to windows azure
Migration of application schema to windows azure
 
R Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioR Tanenbaum .Net Portfolio
R Tanenbaum .Net Portfolio
 
OER Unit 4 Virtual Private Database
OER Unit 4 Virtual Private DatabaseOER Unit 4 Virtual Private Database
OER Unit 4 Virtual Private Database
 
Advanced Apex Security Expert Tips and Best Practices (1).pptx
Advanced Apex Security Expert Tips and Best Practices (1).pptxAdvanced Apex Security Expert Tips and Best Practices (1).pptx
Advanced Apex Security Expert Tips and Best Practices (1).pptx
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
 
Database Security Methods, DAC, MAC,View
Database Security Methods, DAC, MAC,ViewDatabase Security Methods, DAC, MAC,View
Database Security Methods, DAC, MAC,View
 
Row-level security and Dynamic Data Masking
Row-level security and Dynamic Data MaskingRow-level security and Dynamic Data Masking
Row-level security and Dynamic Data Masking
 
Overview on SQL Injection Attacks
Overview on SQL Injection AttacksOverview on SQL Injection Attacks
Overview on SQL Injection Attacks
 
Wellrailed - Be9's Acl9
Wellrailed - Be9's Acl9Wellrailed - Be9's Acl9
Wellrailed - Be9's Acl9
 

Recently uploaded

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

Field Level Security - Spring 20

  • 1. Field Level Security in Apex Learn MOAR in Spring ’20 Rajesh Gupta Senior Tech Lead iBirds Software Services Pvt. Ltd., Ajmer LinkedIn: https://www.linkedin.com/in/bitrajindia
  • 2. Salesforce provides a comprehensive and flexible data security model to secure data at different levels....
  • 3. In Salesforce Data is stored in three key constructions:  Objects  Fields  Records As a Admin, you can control WHO SEE WHAT using Sharing rules, field and object permissions.
  • 4. Salesforce uses  Object-level : Profiles and Permission sets.  Field-level : Profiles also control field-level access.  Record-level security : OWD, Role, Sharing Rules, Manual Sharing
  • 5. In Apex public With Sharing class Sharingclass { //code } public Without Sharing class nonsharing { //code } With sharing keywords when declaring a class enforces Sharing Rules, but not object and field-level permissions
  • 6.  Using Schema Methods  Using WITH SECURITY_ENFORCED clause  Using stripInaccessible Method There are some ways in which you can enforce object-level and field-level permissions in Apex.
  • 7. Check if the Email field on the Contact Object is accessible/readable by the logged in user. if (Schema.sObjectType.Contact.fields.Email.isAccessible()) { Contact c = [SELECT Email FROM Contact WHERE Id= :Id]; } For example,
  • 8. Imagine that you have a bunch of fields in your query, and you have inner queries . This if statement becomes complex to maintain. Drawback:
  • 9. Using WITH SECURITY_ENFORCED clause Starting Spring ‘20, the WITH SECURITY_ENFORCED clause can be used in SOQL queries to enforce field and object level security permissions in Apex code, including subqueries and cross-object relationships. Field-level permissions are checked for all the fields that are retrieved in the SELECT clause(s) of the query. Since this clause only works inside an SOQL query, it’s only useful when you want to check for read access on a field
  • 10. Using WITH SECURITY_ENFORCED clause Example 1: List<Account> act1 = [ SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account WHERE Name like 'Acme' WITH SECURITY_ENFORCED ]; The above query will return the Id and Name of Accounts, and the LastName of the related contacts, only if the user has read access to all of these three fields. If the user doesn’t have access to at least one of these fields, the query throws a System.QueryException exception, and no results are returned. As a best practice, SOQL queries that use this clause, have to be enclosed in a try/catch block, so that errors can be gracefully handled.
  • 11. Using WITH SECURITY_ENFORCED clause try{ List<Account> act1 = [ SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account WHERE Name like 'Acme' WITH SECURITY_ENFORCED ]; } catch(System.QueryException) { //TODO: Handle Errors }
  • 12. Using WITH SECURITY_ENFORCED clause Example 2: List<Contact> contacts = [SELECT Id, Name, BirthDate FROM Contact WHERE Picture_URL__c != null WITH SECURITY_ENFORCED]; However, it is important to note that this clause doesn’t verify field-level security for fields used in the WHERE clause of the query. For example, if a user doesn’t have access a custom field called Picture_URL__c on the Contact object, the below query doesn’t throw an error, and the results are returned as usual.
  • 13. Using stripInaccessible Method The stripInaccessible method from the new Security class to enforce field and object level security in Apex. Like the name suggests, this method can be used to strip the fields from sObject lists to which the user doesn’t have appropriate access, depending on the operation being performed. stripInaccessible(System.AccessType accessCheckType, List<sObject> sourceRecords, [Boolean enforceRootObjectCRUD])
  • 14. Using stripInaccessible Method  accessCheckType: This parameter defines the type of field-level access check to be performed. It accepts System.AccessType enum values: CREATABLE, READABLE, UPDATABLE, UPSERTABLE.  sourceRecords: A list of sObjects to be checked for fields that aren’t accessible in the context of the current user’s operation.  enforceRootObjectCRUD: An optional parameter that indicates whether object-level access check has to be performed. If set to true, and the user doesn’t have the necessary CRUD permissions on the object, this method throws an exception. It defaults to true.
  • 15. Using stripInaccessible Method This method returns an object of type SObjectAccessDecision. You use the getRecords() method to access the list of sObjects which are stripped of fields that fail the field-level security checks for the current user For error handling purposes, you can use the getRemovedFields() method to access a map of sObject types and their corresponding inaccessible fields.
  • 16. Using stripInaccessible Method Here is an example of a DML operation, where the current user doesn’t have access to a custom field Picture_URL__c on the Contact Object: List<Contact> contacts = new List<Contact>{ new Contact(FirstName='Jane', LastName='Doe', Picture_URL__c='someurl'), new Contact(FirstName='John', LastName='Doe', Picture_URL__c='someurl'), }; // Strip fields that are not creatable SObjectAccessDecision decision = Security.stripInaccessible(AccessType.CREATABLE,contacts);
  • 17. //DML try{ insert decision.getRecords(); }catch(NoAccessException e){ //TODO: Handle Error if the user lacks create permission on the Object } // OPTIONAL: Print removed fields System.debug(decision.getRemovedFields());
  • 18. Using stripInaccessible Method The DML operation written above runs successfully without exceptions, but the Picture URL field on the inserted records would be blank because the current user doesn’t have appropriate permissions on it, therefore the value has been stripped off. However, if the user lacked the create permission on the Contact object itself, the DML statement would throw an exception. Here is another example of the method’s usage in a query operation, where the current user doesn’t have access to a custom field Picture_URL__c on the Contact Object.
  • 19. Security.SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.READABLE,[SELECT Name, Picture_URL__c FROM Contact ];); for (Contact c : securityDecision.getRecords()) { system.debug(c.Name); //Prints: Jane, John system.debug(c.Picture_URL__c); //Prints: null, null }
  • 20. Inaccessible fields are removed from the query result, therefore those fields would return a NULL value. If you are using the stripInaccessible method on a list of sObject records that have already been retrieved by a query, remember to use the getRecords() method to access the list of records with inaccessible fields removed. The original list of records is not updated by the stripInaccessible method and would still contain the values of inaccessible fields.
  • 21. List<Contacts> contacts = [SELECT Name, Picture_URL__c from Contact]; Security.SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.READABLE, contacts); system.debug(contacts); //Insecure access system.debug(securityDecision.getRecords()); //Secure access
  • 22. To sum up, this method can be used to:  Strip fields from query results that the user doesn’t have read access to.  Remove inaccessible fields before a DML operation without causing an exception.  Sanitize sObjects that have been deserialized from an untrusted source. Using stripInaccessible Method
  • 23. Summary These new techniques make the code less verbose and more efficient.  The WITH SECURITY_ENFORCED clause can be used directly in an SOQL query to check for read access on fields, and the query will throw an exception if a single field isn’t accessible.  stripInaccessible method can be used in read, create, update and upsert operations to strip the fields from sObject Lists that are inaccessible.
  • 24. Points To Remember -  stripInaccessible method is a preview and isn’t part of the “Services” under your master subscription agreement with Salesforce. This feature is for evaluation purposes only, not for production use. It’s offered as is and isn’t supported, and Salesforce has no liability for any harm or damage arising out of or in connection with it.  The return list is identical to the source records, except that the fields that are inaccessible to the current user are removed. the getRecords method contain records in the same order as the sObjects in the sourceRecords parameter of the stripInaccessible method.  The ID field is never stripped by the stripInaccessible method to avoid issues when performing DML on the result.
  • 25. Points To Remember -  The ID field is never stripped by the stripInaccessible method to avoid issues when performing DML on the result.  The stripInaccessible method doesn’t support AggregateResult SObject. If the source records are of AggregateResult SObject type, an exception is thrown.