Understanding With Sharing and Without Sharing In Salesforce

Sharing is Caring

Security in Salesforce and on the Force.com platform can be really hard to understand. In this blog post, we’re going to have a look at the “With Sharing” and “Without Sharing” Apex keywords.

As you may recall, Apex generally runs in System mode most of the time which means that security can often be minimalized. With Sharing and Without sharing are really poorly understood.

What is Sharing?

Sharing determines what a user is able to do with a particular record based on the Share tables. When sharing is enabled all queries (or DML operations) will be compared against the Share table to see if the user has the needed access to that record.

Keep in mind that we cannot automatically enforce field level security or profile permissions probably because this would make the code really difficult to debug.

This means that if a user tries to update a record they don’t have access to, it will fail and they will get an error. As developers, we need to ensure that our updates are system updates OR if we are doing things on behalf of the user.

If we are doing things on behalf of the user it failing is perfectly okay.

What is “Without Sharing”?

Without Sharing means you are disabling or ignoring sharing rules. It is the default for an Apex class.

If a class is run through Execute Anonymous or in Chatter it will run “With Sharing”. In general, I rarely write “Without Sharing” since the default is “Without Sharing”.

Apex Controller Extensions will inherit whatever the Apex controller is doing.

Why Wouldn’t I Use “With Sharing” all the time?

There are a lot of situations where we might want to allow a user to write or update an object they don’t necessarily have access to. In particular, logging objects we can debug what happened earlier would be a “system action”.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.