Skip to main content

Salesforce

Can We Control Field-Level Security from Apex?

Istock 1646500557

Imagine you are building a Salesforce application and must ensure that users can only access specific fields based on their profiles or permission sets. You might wonder: can we control field-level security (FLS) from Apex? Explore this topic and understand the possibilities, challenges, and best practices.

Understanding Field-Level Security in Salesforce

 Visual Selection (4)

Before we explore Apex, let’s first understand how Salesforce manages field-level security (FLS). FLS controls access to specific fields within an object and determines whether a user can see, edit, or modify a field.

There are multiple ways to configure FLS in Salesforce:

  • Profiles and Permission Sets: You define FLS at the profile or permission set level.
  • Page Layouts: You can restrict field visibility on the UI level.
  • Validation Rules & Triggers: These can enforce field access indirectly.

Now, the big question: Can we enforce FLS dynamically in Apex?

Can Apex Enforce Field-Level Security?

Apex operates in system mode by default, ignoring field-level security and object permissions unless explicitly handled. This means that even if a user cannot access a field, Apex can still retrieve and modify its value.

However, Salesforce provides mechanisms to enforce FLS in Apex:

1. Using Schema.DescribeFieldResult to Check FLS

Salesforce offers the Schema class allows us to check a user’s access to a field before performing operations.

Example:

Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();
if (fieldResult.isAccessible()) {
    System.debug('User has access to the Industry field');
} else {
    System.debug('User does NOT have access to the Industry field');
}

This method ensures that we verify if the user has permission before accessing a field.

2. Using Security.stripInaccessible()

Introduced in Salesforce’s Spring ‘20 release, Security.stripInaccessible() allows you to remove fields that the user does not have permission to access.

Example:

Account acc = [SELECT Id, Name, Industry FROM Account WHERE Id = :someId];
SObject sanitizedAcc = Security.stripInaccessible(AccessType.READABLE, acc);
System.debug(sanitizedAcc);

This prevents Apex from exposing restricted fields when querying records.

Similarly, you can use AccessType.UPDATABLE to prevent unauthorized updates:

update Security.stripInaccessible(AccessType.UPDATABLE, acc);

This is a best practice for handling FLS dynamically.

3. Using WITH SECURITY_ENFORCED in SOQL

Salesforce allows you to enforce FLS directly in SOQL queries using WITH SECURITY_ENFORCED.

Example:

Account acc = [SELECT Id, Name, Industry FROM Account WHERE Id = :someId WITH SECURITY_ENFORCED];

If the user cannot access the Industry field, the query will fail, ensuring data security.

Challenges in Controlling FLS with Apex

 Visual Selection (2)

While Apex provides mechanisms to enforce FLS, there are some challenges:

  • Bulk Operations: When handling large volumes of data, manually checking each field’s accessibility can be inefficient.
  • Complex Business Logic: If logic depends on fields a user cannot access, it can break Apex functionality.
  • UI vs. Backend Enforcement: UI-based restrictions do not apply to backend processing (triggers, batch jobs), requiring additional validation.

Best Practices for Handling FLS in Apex

 Visual Selection (3)

To ensure your Apex code respects FLS, follow these best practices:

  • Always use Security.stripInaccessible() when working with records.
  • Use WITH SECURITY_ENFORCED in SOQL to automatically enforce field security.
  • Check permissions using Schema.DescribeFieldResult before accessing fields in Apex.
  • Document and review FLS enforcement to avoid security loopholes.

4. Using WITH USER_MODE in SOQL

In some scenarios, you might want your Apex queries to execute with the same restrictions as the current user, ensuring that all field-level security and sharing settings are automatically honored. This is where the WITH USER_MODE clause comes into play. When appended to your SOQL query, WITH USER_MODE forces the query to run in user mode, which enforces the same field access and sharing rules that apply to the user interacting with your application.

Example:

Account acc = [SELECT Id, Name, Industry FROM Account WHERE Id = :someId WITH USER_MODE];

In this example, if the logged-in user cannot access the Industry field (or even the record itself due to sharing settings), the query will either filter out that field or return no results, depending on the situation. This clause can simplify your code by reducing the need for manual checks using Schema.DescribeFieldResult or Security.stripInaccessible(). However, it’s important to note that the query will fail at runtime if the user lacks the necessary permissions. As a best practice, consider wrapping such queries in try-catch blocks to gracefully handle potential exceptions.

Conclusion

So, can we control field-level security from Apex? Yes, but not automatically! Apex runs in system mode, meaning you must explicitly enforce FLS using methods like Schema.DescribeFieldResult, Security.stripInaccessible(), and WITH SECURITY_ENFORCED.

Following best practices, you can ensure that your Apex code respects user permissions and keeps data secure. The next time you write an Apex class that interacts with sensitive fields, remember to check field level security before exposing data!

Want to learn more about Salesforce security best practices? Stay tuned for more insightful blogs!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Darshan Kukde

Darshan Kukde is an experienced Salesforce professional with around 4 years of experience in the Salesforce domain. He has worked across Salesforce Sales, Service, Experience, Marketing Cloud, and CPQ. With multiple certifications and a commitment to continuous learning, Darshan excels in crafting innovative solutions that enhance business processes. His passion for technology is reflected in his expertise across various platforms, ensuring he remains at the forefront of industry advancements.

More from this Author

Categories
Follow Us