Sub topic 9
Controlling access to objects and fields
This chapter assumes you can navigate Setup, you know what standard and custom objects are, and you have seen fields and relationships in Object Manager. It covers how Salesforce decides whether a user can see or change an object, a field, or a specific record. It also covers the errors people run into most often.
Three layers of access
Salesforce checks access in layers. A user needs every layer to allow an action before it succeeds.
- Object permissions decide whether a user can read, create, edit or delete records of an object at all.
- Field-level security decides whether a user can see or edit a particular field on that object.
- Record access decides which individual records the user can reach. It is controlled by sharing settings, the role hierarchy, sharing rules, and ownership.
Layers 1 and 2 are the focus of this chapter. They apply the same way to standard objects such as Account and custom objects such as Invoice__c. Layer 3 is covered briefly at the end because it often explains "I have object access but can't see the record."
Object permissions
Each object has up to six permissions.
| Permission | What it allows |
|---|---|
| Read | View records the user can already reach through sharing |
| Create | Create new records |
| Edit | Change records the user can reach |
| Delete | Delete records the user can reach |
| View All | Read all records of the object, ignoring sharing |
| Modify All | Read, edit and delete all records, ignoring sharing |
Edit requires Read. Delete requires Read and Edit. View All and Modify All are powerful because they bypass sharing for that object, so grant them sparingly.
Object permissions are granted through profiles and permission sets. They never reduce access. If a user has Read through one source, no other source can take it away. Access is the union of everything granted.
Profiles and permission sets
A profile is a required, single assignment for each user. It sets baseline access such as object permissions, field permissions, app visibility and login hours. A permission set is an optional bundle of permissions that you can assign to many users, and a user can have many of them. A permission set group combines several permission sets into one assignable unit.
Current Salesforce guidance is to keep profiles minimal and grant extra access with permission sets. Salesforce has announced the retirement of permission editing on profiles, so new designs should not depend on profiles holding detailed permissions.
| Feature | Profile | Permission set |
|---|---|---|
| Per user | Exactly one | Zero or many |
| Can grant access | Yes | Yes |
| Can remove access | No, only grants less | No |
| Best use | Minimal baseline | Job-specific access |
A practical pattern is one permission set per job function, for example "Invoice Viewer" and "Invoice Manager." Each lists the object permissions and field permissions for Invoice__c that the job needs. You then assign them to users, or bundle them into a group.
Creating object access for a custom object
When you create a custom object, no one except administrators can use it until you grant access. A common mistake is to create the object, add a tab, and then wonder why other users report "insufficient privileges" or cannot find the tab. The fix is to grant object permissions and tab visibility in a permission set and assign that set to the users.
A permission set can also be defined as metadata. The following file grants read and create access to Invoice__c, and read and edit access to its Amount__c field.
<?xml version="1.0" encoding="UTF-8"?>
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Invoice Viewer</label>
<hasActivationRequired>false</hasActivationRequired>
<objectPermissions>
<object>Invoice__c</object>
<allowCreate>true</allowCreate>
<allowRead>true</allowRead>
<allowEdit>false</allowEdit>
<allowDelete>false</allowDelete>
<viewAllRecords>false</viewAllRecords>
<modifyAllRecords>false</modifyAllRecords>
</objectPermissions>
<fieldPermissions>
<field>Invoice__c.Amount__c</field>
<readable>true</readable>
<editable>true</editable>
</fieldPermissions>
<tabSettings>
<tab>Invoice__c</tab>
<visibility>Visible</visibility>
</tabSettings>
</PermissionSet>Notice that the field is written as Invoice__c.Amount__c, using API names. Using the API name from the earlier chapter on naming keeps deployments stable even if someone later changes a label.
Field-level security
Field-level security (FLS) sets each field to one of three states for a given profile or permission set: not visible, read-only, or editable. It is granted by the same profiles and permission sets as object permissions.
Some points that surprise people:
- FLS applies to a field wherever it appears, including page layouts, list views, reports, search results, and API access. Hiding a field from a page layout is not security. The field is still returned through the API unless FLS also hides it.
- A field must be on a page layout to appear in the record page, but FLS must also allow it. Both conditions are required for the user to see it in the UI.
- A user with edit permission on a field can still be blocked by a validation rule or by the field being read-only by nature, such as formula fields, auto-number fields and roll-up summary fields.
- Required fields set at the field definition level are always required, regardless of FLS. Making a required field invisible to a user causes problems when that user creates records through the UI or API, so check this when designing.
- For master-detail relationships, the relationship field's access is tied to the parent. For Name fields on standard objects, access is generally always available.
Layout versus security
A page layout controls presentation. FLS controls access. If the goal is only to simplify a screen, use a layout or a Lightning page. If the goal is to prevent a user from seeing a value, use FLS.
How access combines when a user has several sources
Because access is the union of profile and permission sets, troubleshooting is about finding which source grants or fails to grant something. Salesforce provides a View Summary action for a user in Setup. It lists object and field permissions from all sources for that user. For a specific permission, the permission set page and the "Field Accessibility" view in Setup show what each profile or set allows for a given field.
When a user can't see an object or field, check in this order:
- Is the object permission (Read at minimum) granted by the profile or any assigned permission set?
- Is the tab visible, if the user is navigating through a tab?
- Is the field visible under FLS in some source?
- Is the field on the page layout assigned to the user's profile and record type?
- Does record access (sharing) let the user reach the record at all?
Access in code: sharing and enforcement
Apex has a surprising default. Code running in system mode does not enforce the running user's object permissions or FLS. This lets triggers and classes do their work, but it creates a risk when code exposes data to a user who should not see it.
You have these tools:
with sharingon a class makes the code respect record-level sharing rules. It does not enforce object permissions or FLS.WITH USER_MODEin SOQL runs the query with the user's object permissions, FLS and sharing.WITH SECURITY_ENFORCEDis an older clause that checks FLS for fields in the query and throws an exception if one is not accessible. User mode is the recommended replacement.Security.stripInaccessibleremoves fields the user cannot access from records, so you can return the rest.AccessLevel.USER_MODEapplies user permissions to DML operations.
public with sharing class InvoiceService {
public static List<Invoice__c> getOpenInvoices() {
return [
SELECT Name, Amount__c, Status__c
FROM Invoice__c
WHERE Status__c = 'Open'
WITH USER_MODE
];
}
public static void createInvoice(Id accountId, Decimal amount) {
Invoice__c inv = new Invoice__c(
Name = 'INV-NEW',
Account__c = accountId,
Amount__c = amount,
Status__c = 'Open'
);
Database.insert(inv, AccessLevel.USER_MODE);
}
}If the running user lacks Read on Invoice__c or on one of the fields, the query throws a System.QueryException. If the user lacks Create or field edit permission, the insert throws a System.DmlException. Catch these and show a useful message rather than a generic failure.
You can also test access explicitly using the describe methods you saw earlier.
Schema.DescribeSObjectResult d = Invoice__c.SObjectType.getDescribe();
Schema.DescribeFieldResult f = Invoice__c.Amount__c.getDescribe();
System.debug('Can read invoices: ' + d.isAccessible());
System.debug('Can create invoices: ' + d.isCreateable());
System.debug('Can edit amount: ' + f.isUpdateable());These checks reflect the current user's access. They are useful for hiding buttons in custom UI, but they are not a replacement for enforcing access in the query or DML.
Record access in brief
Object permission only says a user may work with an object. Which records they can reach depends on:
- Organization-wide defaults (OWD), the baseline for each object: Private, Public Read Only, Public Read/Write, or Controlled by Parent.
- Role hierarchy, which lets managers see the records of people below them, when "Grant Access Using Hierarchies" is on.
- Sharing rules, which open access to groups of users based on owner or criteria.
- Manual sharing and teams, for individual records.
- Ownership, since owners generally have access to their own records.
Sharing can only open access further than the OWD. It cannot restrict it. Controlled by Parent applies to the detail side of a master-detail relationship, so the detail's access follows the master record. This is one reason the choice between lookup and master-detail, covered in the relationships chapter, affects security design.
Common errors
| Symptom | Likely cause |
|---|---|
| "Insufficient privileges" on a new custom object | No permission set grants object access to the user |
| Field missing on the record page | FLS hides it, or it is not on the assigned layout |
| Field hidden in the UI but visible via API | Only the layout was changed, not FLS |
| Query returns fewer records than expected | Sharing limits the records, even with Read permission |
| Apex returns data a user should not see | Class runs in system mode without `WITH USER_MODE` or stripInaccessible |
| Permission removed from a profile but user still has it | Another permission set or group grants it |
Exercise
A user has Read permission on Invoice_c through a permission set, and Amountc is editable in the same set. The user opens an invoice record owned by another team and gets an "insufficient privileges" message. The OWD for Invoice_c is Private and the user is not above the owner in the role hierarchy. What is the cause, and what are two ways to fix it?
Show answer
Object and field permissions are satisfied, but record access fails because the OWD is Private and nothing shares the record with the user. Fixes: create a sharing rule that shares the records with the user's role or group, or share the specific record manually. Granting View All on Invoice__c would also work, but it opens every invoice, so it is a broader fix.
Exercise
A developer writes an Apex class marked with sharing that runs SELECT Name, Amount_c FROM Invoicec with no other clauses. A user who lacks FLS on Amountc calls it from a custom component. Does the user see Amount_c? What change enforces FLS?
Show answer
Yes, the user can see it. with sharing enforces record-level sharing only, not object permissions or FLS, so the query returns the field. Add WITH USER_MODE to the query, or pass the results through Security.stripInaccessible, so FLS is enforced.