
- 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 - 單擊“儲存”按鈕。