‘With Sharing’ Keyword

Recently I came across a rather confusing situation with my Force.com application. I had whittled down my profiles; implemented a marvelous role hierarchy; and a number of sharing rules, and although my application was functionally restricted i.e. object-level access, field-level access etc., the data didn’t seem to be restricted by the sharing model i.e. I could see data created by user A when logged in as user B, even though I had explicitly disabled this behaviour.

The application I’m developing may not be the same or even similar to yours, especially since I don’t use any standard pages. I suspect that if I had use more of the standard functionality I may have guessed at the solution a bit earlier. Anyway this is what I noticed in my investigations,

  1. Pages that displayed lists of records were showing the data for all users, even though they shouldn’t.
  2. Clicking on a record in order to view the detail page brought up an ‘Unauthorised Access’ error.

So there I was like a drunken monkey scratching my head and thinking in circles.. I can see the record but I can’t view it’s detail. But I can see the records.. but I can’t VIEW it’s detail. But I can see the..

And this was my conclusion,

  1. I’m stuck.

I contacted Salesforce giving them the detail and a little while later they gave me this little gem of information. And I paraphrase

Apex code runs in system context so that the current user’s profile-based permissions, field-level security, and sharing rules are ignored. You can use the ‘with sharing’ keywords to enforce the sharing rules that apply to the current user.

This makes sense. Sort of. It doesn’t really explain why I could see some of the record data(as listed on one page) but not view the detail of the same records on another page. But it worked, and that’s what’s important. And example would be

public MyClass{

// Contents

}

becomes

public with sharing MyClass{

// Contents

}

A simple solution, and one that is documented but difficult to find. Anyone looking for more details can find them here.

11 thoughts on “‘With Sharing’ Keyword”

  1. hi..

    we are also incorporate some issues in “With Sharing” keyword.

    in my VF page i m using the “with Sharing” keyword in my controller class but it not respect the permissions

    user A have no permission to create the case.
    now we have VF page for creating the case. i m using “with sharing” keyword in my controller.

    now i m log in as user A and trying to create the case from that VF page it will allow me to create the case though user A don’t have case create permission.

    How do i solve this issue..

    please suggest your thoughts on this issues..

    Thanks
    Amar

    Reply

Leave a Comment