在 Salesforce 中,FLS控制用户能访问哪些对象、哪些字段。但 Apex 默认运行在 系统模式(System Mode) 下,会忽略这些安全限制。
为了在代码中强制执行安全控制,我们需要:
使用 WITH SECURITY_ENFORCED
SELECT Id, Salary__c FROM Employee__c WITH SECURITY_ENFORCED;
如果用户没有访问字段或对象的权限,会在运行时报错。
使用 Schema 方法手动检查
if (Schema.sObjectType.Employee__c.fields.Salary__c.**isAccessible**()) {
// 安全读取字段
}
执行 DML 前检查 CRUD
if (Schema.sObjectType.Account.**isCreateable**()) { insert accList; }
总结一句:
因为 Apex 是系统模式运行的,所以要在代码中主动加上安全检查,确保遵守用户权限。
In Salesforce, object-level and field-level security (FLS) control what data a user can access.
However, Apex runs in system mode, so it ignores these restrictions by default.
To enforce them in code, we can:
Use WITH SECURITY_ENFORCED in SOQL to automatically check both CRUD and FLS:
SELECT Id, Salary__c FROM Employee__c WITH SECURITY_ENFORCED;
→ This throws a runtime error if the user doesn’t have access to the object or field.
Use Schema methods before DML or field access:
if (Schema.sObjectType.Employee__c.fields.Salary__c.isAccessible()) {
// safely access field
}
For CRUD checks, use:
if (Schema.sObjectType.Account.isCreateable()) { insert accList; }
So, developers should always check CRUD before DML, and FLS before field read/write, especially when exposing data through API or Lightning components.
In short:
Apex runs in system mode — so always add security checks to respect the user’s permission model.