Thursday, 21 July 2022

A new way to enforce user level security with Apex code

By the release of Summer 22, Major expansion in the Apex security model. Now we can declare Apex database operations run on user or system modes. In this blog, we will see how to write Secure Apex Code with User Mode Database Operations (Summer '22 release) in a remarkably simplified manner. This feature is currently under Beta.

The new Database methods support an AccessLevel parameter that lets you run database operations in user mode instead of in the default system mode. By default Apex code runs in system mode,  Which means that it runs with substantially elevated permissions over the user running the code. To enhance the security context of Apex, you can specify user mode access for database operations. Field-level security (FLS) and object permissions of the running user are respected in user mode, unlike in system mode. User mode always applies sharing rules. in system mode they’re controlled by the class sharing keywords.

USER_MODE AND SYSTEM_MODE

In SOQL queries we can indicate the mode of the operation by using USER_MODE or SYSTEM_MODE. Below is an example that specifies the user mode.

List<Account> accts = [SELECT Id, Name, Phone, BillingCity FROM Account WITH USER_MODE];

List<Contact> cons = [SELECT Id, FirstName, LastName, Account.Name FROM Contact WITH USER_MODE]; 

Database operation with USER or SYSTEM MODE

Database operations can specify user or system mode. Below is an example to insert a new account with user mode.

Account acct = new Account(
    Name='Binary Republik',
    Phone='9909950592');

insert as USER acct;

Account acc = [SELECT Id, Name, Phone FROM Account WHERE Name ='Binary Republik'];

acc.Email = 'info@binaryrepublik.com';
update as SYSTEM acc; 
 

Dynamic at runtime syntax

The new AccessLevel class represents the two modes in which Apex runs database operations. Use this new class to define the execution mode as user mode or system mode. Use these new overloaded methods to perform DML and query operations.
  • Database.query methods
  • Search.query methods
  • Database DML methods (insert, update, upsert, merge, delete, undelete, and convertLead)
Below are some examples.
//Database.query example

Account acc = Database.query('SELECT Id, Name FROM Account WHERE Name = 'Binary Republic'', AccessLevel.USER_MODE);

//Database.insert example

Database.insert(new Account(Name = 'Binary Republik'),AccessLevel.USER_MODE);

Click here see release notes on secure apex Code with user mode database operations. 


If you have any questions you can reach out our Salesforce Consulting team here.

No comments:

Post a Comment