Saturday, July 12, 2025

User Mode vs WITH SECURITY_ENFORCED in Apex


Feature / Aspect

User Mode

WITH SECURITY_ENFORCED

Purpose

Enforces user permissions (FLS & CRUD) automatically in SOQL and DML

Enforces FLS & CRUD in SOQL only

Scope

Works with SOQL, DML, Async Apex (Batch, Queueable, etc.)

Works only with SOQL

Syntax Example

Database.query(new Query("SELECT Name FROM Account").setUserMode(UserMode.CURRENT));

[SELECT Name FROM Account WITH SECURITY_ENFORCED];

Field-Level Security (FLS)

Respected automatically

Respected, but throws error if access is denied

Object-Level Security (CRUD)

Respected automatically

Respected, but throws error if access is denied

Partial Access Handling

Returns only accessible fields/objects

Fails completely if any field/object is restricted

Error Handling

No error thrown for restricted fields; they are silently excluded

Throws uncatchable exception if access is denied

Support for Relationship Fields

✅ Supported

❌ Not supported (e.g., Owner.Name fails)

Support in Dynamic SOQL

✅ Fully supported

❌ Not supported

Support in DML Operations

✅ Supported via Database.DMLOptions.setUserMode()

❌ Not supported

Async Apex Compatibility

✅ Works in Batch, Queueable, etc.

❌ Not supported

Ease of Use

Cleaner, safer, and more flexible

Requires careful handling and limited in scope

Salesforce Recommendation

✅ Recommended

❌ Not recommended anymore

Use Case Example

Secure insert: Database.insert(record, dmlOpts);

Secure query: [SELECT Name FROM Account WITH SECURITY_ENFORCED];

Limitations

Few limitations; more flexible

Many limitations (no dynamic SOQL, no DML, no async, no partial results)

Can Be Used Together?

❌ Cannot be combined with WITH SECURITY_ENFORCED

❌ Cannot be combined with UserMode

No comments:

Post a Comment