Pages

Monday 10 June 2019

Enforce Field-Level Security in Apex (Pilot)

Apex has a new security feature for field-level data protection, which is accessed through the Security and SObjectAccessDecision classes. To ensure secure processing in Apex in the context of the current user’s read, create, or update operation, use the stripInaccessible method. Based on the field-level security of the current user, this method can be used to strip the fields from query results that the user can’t access. The method can also be used to remove inaccessible fields from sObjects before a DML operation to avoid exceptions and to sanitize sObjects that have been deserialized from an untrusted source.
How: The stripInaccesible method checks the source records for fields that don’t meet the field-level security check for the current user and creates a return list of sObjects. The return list is identical to the source records, except that the fields that are inaccessible to the current user are removed.

Example
If the user doesn’t have the permission to create the Probability field of an Opportunity object, this example removes the Probability field before creating the records. The DML operation is completed without throwing an exception.


List<Opportunity> opportunities = new List<Opportunity>{
    new Opportunity(Name='Opportunity1'),
    new Opportunity(Name='Opportunity2', Probability=95)
};

// Strip fields that are not creatable
SObjectAccessDecision decision = Security.stripInaccessible(
    AccessType.CREATABLE,
    opportunities);

// Print stripped records
for (SObject strippedOpportunity : decision.getRecords()) {
    System.debug(strippedOpportunity);
}

// print modified indexes
System.debug(decision.getModifiedIndexes());

// Print removed fields
System.debug(decision.getRemovedFields());

//System.debug Output
// DEBUG|Opportunity:{Name=Opportunity1}
// DEBUG|Opportunity:{Name=Opportunity2}
// DEBUG|{1}
// DEBUG|{Opportunity={Probability}}

No comments :

Post a Comment