1

When doing SOQL Queries, how I can I ensure that I only return the set of Objects that the current user has access to?

Imagine I query for Accounts, and I display a list of links to those Accounts on a VisualForce page. I only want to list those Accounts that the user has access to, otherwise the user clicks on a link but will get an Access Denied, which is not what we want.

How do I do that?

2

1 Answer 1

7

Define the class that your SOQL query is within as with sharing.

This is covered by the online documentation here.

The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class. You have to explicitly set this keyword for the class because Apex code runs in system context. In system context, Apex code has access to all objects and fields— object permissions, field-level security, sharing rules aren’t applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or objects for a user.

And here is an example:

Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For example:

public with sharing class sharingClass 
{
    // Code here
}
1
  • Excellent. Exactly what I need. Commented Feb 14, 2014 at 11:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .