
- Apex编程教程
- Apex - 首页
- Apex - 概述
- Apex - 环境
- Apex - 示例
- Apex - 数据类型
- Apex - 变量
- Apex - 字符串
- Apex - 数组
- Apex - 常量
- Apex - 决策制定
- Apex - 循环
- Apex - 集合
- Apex - 类
- Apex - 方法
- Apex - 对象
- Apex - 接口
- Apex - DML
- Apex - 数据库方法
- Apex - SOSL
- Apex - SOQL
- Apex - 安全性
- Apex - 调用
- Apex - 触发器
- Apex - 触发器设计模式
- Apex - 限制
- Apex - 批处理
- Apex - 调试
- Apex - 测试
- Apex - 部署
- Apex有用资源
- Apex - 快速指南
- Apex - 资源
- Apex - 讨论
Apex - 安全性
Apex 安全性是指应用安全设置并对运行代码强制执行共享规则的过程。Apex 类具有可以通过两个关键字控制的安全设置。
数据安全和共享规则
Apex 通常在系统上下文中运行,即当前用户的权限。在代码执行期间,不会考虑字段级别安全性以及共享规则。只有匿名代码块以执行代码的用户的权限执行。
我们的 Apex 代码不应将通过安全和共享设置隐藏的敏感数据暴露给用户。因此,Apex 安全性和强制执行共享规则至关重要。
使用 With Sharing 关键字
如果使用此关键字,则 Apex 代码将对 Apex 代码强制执行当前用户的共享设置。这不会强制执行配置文件权限,只会强制执行数据级别的共享设置。
让我们考虑一个示例,其中我们的用户可以访问 5 条记录,但记录总数为 10 条。因此,当 Apex 类用“With Sharing”关键字声明时,它只返回用户可以访问的 5 条记录。
示例
首先,确保您已在客户对象中创建至少 10 条记录,其中 5 条记录的“名称”为“ABC 客户”,其余 5 条记录为“XYZ 客户”。然后,创建一个共享规则,将“ABC 客户”与所有用户共享。我们还需要确保已将客户对象的 OWD 设置为私有。
将下面给出的代码粘贴到开发者控制台中的匿名代码块。
// 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();
不使用 Sharing 关键字
顾名思义,使用此关键字声明的类在系统模式下执行,即,与用户对记录的访问权限无关,查询将获取所有记录。
// 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 类安全性
步骤 1 - 在“设置”中,单击“开发”→“Apex 类”。

步骤 2 - 单击要限制的类的名称。我们已单击 CustomerOperationClass。

步骤 3 - 单击“安全性”。

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

步骤 5 - 单击“保存”。
从权限集设置 Apex 安全性
步骤 1 - 在“设置”中,单击“管理用户”→“权限集”。

步骤 2 - 选择一个权限集。

步骤 3 - 单击“Apex 类访问”。

步骤 4 - 单击“编辑”。

步骤 5 - 从“可用 Apex 类”列表中选择要启用的 Apex 类,然后单击“添加”,或者从“已启用 Apex 类”列表中选择要禁用的 Apex 类,然后单击“移除”。

步骤 6 - 单击“保存”按钮。