WITH SECURITY_ENFORCED in Salesforce Apex

Why do we use WITH SECURITY_ENFORCED in SOQL queries?

Apex generally runs in system context, which means that it does not take into consideration the the current user’s permissions and field-level security. This causes a problem because if you include a field in a SQOL query that a user doesn’t have access to, the field is returned and can be used by the code, thus exposing the data to someone that should not have access to it.

What is the difference between WITH SECURITY_ENFORCED and WITH SHARING?

An important thing to note here is that WITH SECURITY_ENFORCED clause is different from the with sharing or without sharing keywords. When using with sharing keyword you are enforcing record access, unlike the WITH SECURITY_ENFORCED clause which is used to enforce Field and Object level security.

Enforcing Field Level Security in Visualforce Pages

Visualforce Standard Controller runs in User Context, which means that Object and Field level security is automatically enforced when using Standard Controller.

Visualforce:

Apex Controller:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store