Recently Salesforce released a new feature in winter 19 which can help administrators ensure field level security in Apex classes.
The feature which is still in pilot phase, can be used to strip the fields which are not accessible by the current user in the DML operations.
Before Winter ’19, apex would run is System Context, meaning even if the user does not have access to those fields, he can still query them and even update them.
Let’s say a user does not have access to “Commission” field on Opportunity object. Now earlier in System context, when the user runs the following query, he would get to see the see the commission data for all opportunities.
Opportunity opp=[Select Name, Commission__c from Opportunity];
With the new feature, Admin can strip the access to the fields which user does not have access to. For example, if we modify the above :
Opportunity opp=[Select Name, Commission__c from Opportunity]; SObjectAccessDecision decision = Security.stripInaccessible( AccessType.READABLE, opportunities); System.debug((List<Opportunity>) decision.getRecords());
With the above example, system will strip off Commission field from the returned data and only show the Opportunity name.
What if user does not have access to the Opportunity object ?
Well in that case, user will see an error page with failure of the action that he was doing. And debug logs will show “No access to entity: Opportunity” message.
Overall, the feature looks worthy. Though it is still in pilot phase, so changes are possible before going to production.
You can also read about the Winter ’19 release here: https://releasenotes.docs.salesforce.com/en-us/summer19/release-notes/rn_apex_Security_stripInaccessible.htm