Enforcing Apex Security With Sharing Keywords

April 21st, 2010

Security is a major foundation of the Force.com platform. Not only is security available declaratively but it is also baked into the Apex language itself. Most Apex scripts run in system context without respect to the current users permissions, sharing rules and field level security. This ensures that triggers and web services have access to all records in the org which is usually a good thing.

However, to ensure that you don’t expose sensitive data to unauthorized users, you can specify that an Apex script does enforce the running user’s profile-based permissions, field-level security, and org-wide defaults by using the with sharing keywords when declaring your class. This can affect SOQL and SOSL queries as well as DML operations.

public with sharing class MyClass {
// class implementation
}

You can also use the without sharing keywords to ensure that Apex scripts do not enforce the sharing rules of the running user.

public without sharing class MyClass {
// class implementation
}

It’s best practices to use these keywords with declaring new classes as if they are not used, the current sharing rules remain in effect. For example, if a class without sharing keywords specified is called by another class, then the sharing is enforced by the first class.

You can also declare inner classes and outer classes as with sharing as well. The sharing setting applies to all code contained in the class, including initialization code, constructors, and methods but inner classes do not inherit the sharing setting from their container class.

Once exception is executeAnonymous which always executes using the full permissions of the current user.


Categories: Apex, Salesforce

Leave a comment

Comments Feed2 Comments

  1. Sanket

    Hi Jeff,
    i have one requirement where i need to get all the methods and the parameters associated with a class. From IDE using eclipse we can use apexclass object to get the whole class but nowhere i could find anything that will give me methods in class. Is there any way to do that?

  2. Jeff Douglas

    Unfortunately there is no introspection of methods as of now. You could submit this as an Idea! I’d vote for it.

Leave a comment

Feed

http://blog.jeffdouglas.com / Enforcing Apex Security With Sharing Keywords

WordPress Appliance - Powered by TurnKey Linux