目录

Apex - 安全( Security)

Apex安全性是指应用安全设置并对运行代码强制执行共享规则的过程。 Apex类具有可通过两个关键字控制的安全设置。

数据安全和共享规则

Apex通常在系统上下文中运行,即当前用户的权限。 在代码执行期间不考虑字段级安全性和共享规则。 只有匿名块代码在执行代码的用户的许可下执行。

我们的Apex代码不应将敏感数据暴露给通过安全和共享设置隐藏的用户。 因此,Apex安全性和执行共享规则是最重要的。

使用共享关键字

如果您使用此关键字,则Apex代码将强制执行当前用户对Apex代码的共享设置。 这不会强制执行配置文件权限,只会强制执行数据级别共享设置。

让我们考虑一个例子,其中,我们的用户可以访问5条记录,但记录总数为10.因此,当Apex类将使用“With Sharing”关键字声明时,它将仅返回用户的5条记录有权访问。

Example

首先,确保您在Customer对象中创建了至少10条记录,其中“Name”为5条记录为“ABC Customer”,其余5条记录为“XYZ Customer”。 然后,创建一个共享规则,该规则将与所有用户共享“ABC客户”。 我们还需要确保将Customer对象的OWD设置为Private。

将下面给出的代码粘贴到Developer Console中的Anonymous块。

// Class With Sharing
public with sharing class MyClassWithSharing {
   // Query To fetch 10 records
   List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10];
   public Integer executeQuery () {
      System.debug('List will have only 5 records and the actual records are' 
         + CustomerList.size()+' as user has access to'+CustomerList);
      Integer ListSize = CustomerList.size();
      return ListSize;
   }
}
// Save the above class and then execute as below
// Execute class using the object of class
MyClassWithSharing obj = new MyClassWithSharing();
Integer ListSize = obj.executeQuery();

没有共享关键字

顾名思义,使用此关键字声明的类在系统模式下执行,即,无论用户是否访问记录,查询都将获取所有记录。

// Class Without Sharing
public without sharing class MyClassWithoutSharing {
   List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10];
   // Query To fetch 10 records, this will return all the records
   public Integer executeQuery () {
      System.debug('List will have only 5 records and the actula records are'
         + CustomerList.size()+' as user has access to'+CustomerList);
      Integer ListSize = CustomerList.size();
      return ListSize;
   }
}
// Output will be 10 records.

设置Apex类的安全性

您可以为特定配置文件启用或禁用Apex类。 下面给出了相同的步骤。 您可以确定哪个配置文件应该有权访问哪个类。

从类列表页面设置Apex类安全性

Step 1 - 从“设置”中,单击“开发”→“Apex类”。

设置Apex Cass安全性Step1

Step 2 - 单击要限制的类的名称。 我们点击了CustomerOperationClass。

设置Apex Cass安全性Step2

Step 3 - 单击安全性。

设置Apex Cass安全性Step3

Step 4 - 从“可用配置文件”列表中选择要启用的配置文件,然后单击“添加”,或从“启用的配置文件”列表中选择要禁用的配置文件,然后单击“删除”。

设置Apex类安全性Step3

Step 5 - 单击“保存”。

从权限集设置Apex安全性

Step 1 - 从“设置”中,单击“管理用户”→“权限集”。

从权限集Step1设置Apex类安全性

Step 2 - 选择权限集。

从权限集Step2设置Apex类安全性

Step 3 - 单击Apex Class Access。

从权限集设置Apex类安全性Step3

Step 4 - 单击“编辑”。

从权限集设置Apex类安全性Step4

Step 5 - 从Available Apex Classes列表中选择要启用的Apex类,然后单击Add,或从Enabled Apex Classes列表中选择要禁用的Apex类,然后单击remove。

从权限集设置Apex类安全性Step5

Step 6 - 单击“保存”按钮。

<上一篇.Apex - SOQL
↑回到顶部↑
WIKI教程 @2018