APEX Security is easier than thought

Topic: WITH SECURITY_ENFORCED, stripInaccessible and Schema.DescribeSObjectResult
Target Group: Developers, Architects
Complexity: Medium

Going down the ISV route taught me an important lesson, enforcing Field and Object Level Security is much easier than thought.

As we all know, APEX runs in System Mode, great in some cases but really bad in most cases (IMHO). I’d love to have a “WITH SECURITY” keyword similar to WITH SHARING.

From my personal experience, coding for clients we most often don’t check for Object and Field Level security.
But since security and trust is the number one issue in our solutions, we should actually do it. I plan always to do it going forward.

I always had the impression adding proper security to code is quite painful with a lot of extra code and negative performance implications.

This all changed in the last few years. WITH SECURITY_ENFORCED and stripInaccessible make it a breeze.

My personal favorite: WITH SECURITY_ENFORCED for SOQL Queries costs almost nothing in performance and immediately stops retrieval of data not supposed to be queried.
In case I want to be a little more graceful, stripInaccessible provides a lot of flexibility. Unfortunately, it comes with a slight performance impact. I use that for special use-cases.
Lastly, trusted “Schema.DescribeSObjectResult”. In case I want to do basic checks like “Is the user allowed to create Opportunities?”, this is an easy way to go about it.

Adding String.escapeSingleQuotes to every Database.Query and WITH SHARING to every class and most security issues are taken care of.

For more info, this article summarizes it really nicely by Jan Binder.

PS: Of course, any errors should be handled gracefully.