WITH SECURITY_ENFORCED and Security.stripInaccessible in a single SOQL

apexfield-level-securitySecuritystripinaccessiblewith-sharing

Premise: I followed WITH SECURITY_ENFORCED, Security.stripInaccessible and comparison before designing my Apex class for querrying a few records.

Doubt:
I implemented my SOQL as

Security.stripInaccessible(AccessType.READABLE,
        [SELECT Id, Name FROM CustObj__c WHERE Name IN: custObjNameListJSON WITH SECURITY_ENFORCED]).getRecords();

So, I just wanted to know implementing both 'WITH SECURITY_ENFORCED' and 'Security.stripInaccessible' in a single SOQL is a bit too extra for the system or should both be applied if I have to check for Object and field level security.

With comparison I understood that stripInaccessible does NOT respect for sharing rule while WITH SECURITY_ENFORCED will throw error at the time of inaccesible field, so should we always use the combination or will it be extra effort for the system.

Note: I already have with sharing in my class.

Best Answer

You don't need both. If you use WITH SECURITY_ENFORCED, you'll get an exception thrown if any fields are not readable by the user, while with Security.stripInaccessible, you'll simply remove any values that the user shouldn't see.

In other words, use the former if your code cannot proceed without retrieving the fields, or use the latter if you want to still proceed with whatever data the user can see.

Note that neither of these functions apply to Record Level Security; using with sharing or inherited sharing will ensure that users cannot query records they should not be able to see.

Related Topic