この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

共有ルールの適用

Apex は一般に、システムコンテキストで実行されます。つまり、コード実行時に、現在のユーザの権限、項目レベルセキュリティ、および共有ルールは考慮されません。

このルールの唯一の例外は、executeAnonymous コールおよび Chatter in Apex と共に実行される Apex コードです。executeAnonymous は常に、現在のユーザのフル権限を用いて実行されます。executeAnonymous の詳細は、「匿名ブロック」を参照してください。

メモ

これらのルールは強制されないため、Apex を使用する開発者は、ユーザ権限、項目レベルのセキュリティ、または組織のデフォルト設定によって通常は非表示となる機密データが不注意で公開されないようにする必要があります。Web サービスについては特に注意が必要です。Web サービスは権限によって制限できますが、初期化された後はシステムコンテキストで実行されます。

多くの場合、システムコンテキストは、組織内のすべてのデータへのアクセスが必要なトリガや Web サービスなど、システムレベルの操作に対して、正しい動作を設定します。ただし、特定の Apex クラスが現在のユーザに適用されている共有ルールを強制実行するように指定することもできます (共有ルールの詳細は、Salesforce オンラインヘルプを参照してください)。

with sharing キーワードを使用した共有ルールを強制実行しても、ユーザの権限および項目レベルセキュリティは適用されません。Apex コードには、組織のすべての項目およびオブジェクトへのアクセス権が常にあるため、項目またはオブジェクトがユーザに対して非表示であるためにコードの実行が失敗することはありません。

メモ

次の例には 2 つのクラスがあり、1 番目のクラス (CWith) では、共有ルールが適用されますが、2 番目のクラス (CWithout) では適用されません。CWithout クラスでは、メソッドが 1 番目のクラスからコールされ、適用された共有ルールで実行されます。CWithout クラスには内部クラスが含まれます。このクラスでは、コール側と同じ共有コンテキストでコードが実行されます。また、クラスを拡張するクラスが含まれています。これにより、共有設定なしでクラスが継承されます。

1public with sharing class CWith {
2  // All code in this class operates with enforced sharing rules.
3
4  Account a = [SELECT . . . ];
5
6  public static void m() { . . . }
7  
8  static {
9    . . .
10  }
11
12  {
13    . . .
14  }
15
16  public void c() {
17    . . .
18  } 
19}
20
21public without sharing class CWithout {
22  // All code in this class ignores sharing rules and operates 
23  // as if the context user has the Modify All Data permission.
24  Account a = [SELECT . . . ];
25  . . .
26
27  public static void m() {  
28     . . . 
29
30    // This call into CWith operates with enforced sharing rules
31    // for the context user. When the call finishes, the code execution 
32    // returns to without sharing mode.
33    CWith.m();
34  }
35
36
37  public class CInner {
38    // All code in this class executes with the same sharing context
39    // as the code that calls it. 
40    // Inner classes are separate from outer classes.
41    . . .
42
43    // Again, this call into CWith operates with enforced sharing rules
44    // for the context user, regardless of the class that initially called this inner class.
45    // When the call finishes, the code execution returns to the sharing mode that was used to call this inner class.
46    CWith.m();
47  }
48
49  public class CInnerWithOut extends CWithout {
50    // All code in this class ignores sharing rules because
51    // this class extends a parent class that ignores sharing rules.
52  }
53}

with sharing として宣言されたクラスが、without sharing として動作するコードをコールしないという保証はありません。そのため、クラスレベルのセキュリティは常に必要となります。さらに、PriceBook2 を使用するすべての SOQL または SOSL クエリは、with sharing キーワードを無視します。適用された共有ルールに関わらず、すべての PriceBook レコードが返されます。

警告

現在のユーザの共有ルールを強制実行すると次のような影響があります。
  • SOQL および SOSL クエリ。クエリがシステムコンテキストで動作する場合より少ない行を返す場合があります。
  • DML 操作。現在のユーザに正しい権限が付与されていない場合、操作が失敗する場合があります。たとえば、ユーザが組織内に存在する外部キー値を指定したものの、現在のユーザにはそのキー値へのアクセス権が付与されていない場合などです。