Sub topic 13
Checking access with schema describe methods
This chapter covers the schema describe methods, which let Apex test a user's field access before it touches a field. It assumes you know basic Apex and SOQL. It also assumes you know that Apex runs in system mode by default, so it ignores field-level security (FLS) unless you add a check. Earlier chapters showed WITH USER_MODE and Security.stripInaccessible. Describe checks are the older, manual way to get the same protection.
What describe checks do
Every field in Apex has a describe result. The describe result is an object that reports metadata about the field, including what the running user is allowed to do with it. You reach it through the Schema namespace:
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.AnnualRevenue;The result has methods that answer yes/no questions about the current user:
| Method | Returns true when the user can... | Related FLS setting |
|---|---|---|
| `isAccessible()` | read the field | Read |
| `isCreateable()` | set the field on a new record | Edit, plus object Create |
| `isUpdateable()` | change the field on an existing record | Edit, plus object Edit |
The same pattern exists at object level on DescribeSObjectResult: isAccessible(), isCreateable(), isUpdateable() and isDeletable(). These check object permissions (CRUD), not FLS. A complete check often needs both levels.
A describe check never changes what the code can do. It returns a Boolean, and your code must act on it. If you forget to branch on the result, nothing is enforced.
Checking one field before an update
The core pattern is to test, then act:
public with sharing class AccountRevenueService {
public class AccessException extends Exception {}
public static void setRevenue(Id accountId, Decimal revenue) {
if (!Schema.sObjectType.Account.isUpdateable()
|| !Schema.sObjectType.Account.fields.AnnualRevenue.isUpdateable()) {
throw new AccessException('You cannot edit Annual Revenue.');
}
Account acc = new Account(Id = accountId, AnnualRevenue = revenue);
update acc;
}
}This does three things in order. It checks the object-level edit permission. It checks the field-level edit permission. Only then does it run the DML. If either check fails, it throws an exception that a caller can handle.
The class uses with sharing. That keyword enforces record sharing rules only. It does not enforce FLS or object permissions, which is why the describe checks are still needed.
Checking before reading
For reads, check isAccessible() for every field you query and return. Here a method builds its query only from fields the user can read:
public with sharing class AccountReader {
public static List<Account> getAccounts() {
List<String> fields = new List<String>{ 'Id', 'Name' };
if (Schema.sObjectType.Account.fields.AnnualRevenue.isAccessible()) {
fields.add('AnnualRevenue');
}
String soql = 'SELECT ' + String.join(fields, ', ')
+ ' FROM Account LIMIT 50';
return Database.query(soql);
}
}The caller must now cope with a missing field. If code later reads acc.AnnualRevenue on a record queried without it, Apex throws a System.SObjectException ("SObject row was retrieved via SOQL without querying the requested field"). A describe check prevents the security leak but moves the burden of handling absent fields to you.
Checking fields dynamically
Static references like Schema.sObjectType.Account.fields.AnnualRevenue fail at compile time if the field does not exist. That is useful, because deleting a field breaks the build instead of silently skipping the check. When field names arrive as strings, use the dynamic form:
public with sharing class FieldAccessChecker {
public static Boolean canRead(String objectName, String fieldName) {
Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName);
if (objType == null) {
return false;
}
Schema.SObjectField field = objType.getDescribe().fields.getMap().get(fieldName);
if (field == null) {
return false;
}
return field.getDescribe().isAccessible();
}
}Note that the helper fails closed. An unknown object or field returns false, never true. Failing closed is the safe default for any access check.
Schema.getGlobalDescribe() is expensive on orgs with many objects. If you only need one object, Type.forName or ((SObject) Type.forName(objectName).newInstance()).getSObjectType() can be lighter. For a fixed object, prefer the static form.
Checking many fields at once
Looping over many fields is repetitive. A helper can check a whole set and report the failures:
public with sharing class BulkFieldCheck {
public static List<String> unreadableFields(
Schema.SObjectType objType, List<String> fieldNames
) {
Map<String, Schema.SObjectField> fieldMap =
objType.getDescribe().fields.getMap();
List<String> blocked = new List<String>();
for (String name : fieldNames) {
Schema.SObjectField f = fieldMap.get(name);
if (f == null || !f.getDescribe().isAccessible()) {
blocked.add(name);
}
}
return blocked;
}
}Call getMap() once outside the loop. Calling it per field repeats work and counts against your describe limits.
Describe checks compared with the other tools
| Approach | Failure behavior | Effort | Best for |
|---|---|---|---|
| `WITH USER_MODE` / `AccessLevel.USER_MODE` | Throws an exception | Lowest | Most new code |
| `Security.stripInaccessible` | Silently removes fields | Low | Returning records to a client |
| Describe checks | You decide | Highest | Per-field logic, custom messages, older API versions |
Describe checks make sense when you need a custom response per field, such as showing a different message or skipping one optional field while still processing the rest. For ordinary enforcement, user mode is shorter and harder to get wrong, because it covers every field in the query automatically.
Gotchas
- Checks cover only the fields you name. Add a field to the query later and forget the check, and that field leaks. User mode does not have this weakness.
- Relationship fields are separate fields. A query on
Account.Owner.Emaildepends on access toUser.Email, not just the Account fields. Check the field on the related object. - Describe reflects the running user. In a test, call the check inside
System.runAs. Outside it, you test the test runner's access, which is usually an administrator's. - Object access is separate. A field can be editable while the user lacks Edit on the object.
isUpdateable()on a field does not cover object permissions in every case, so check both, as the first example did. - Some fields are never writable. System and formula fields return
falseforisUpdateable()for everyone, whatever the FLS says. Afalseresult does not always mean a permission problem. - Describe checks do not guard dynamic SOQL by themselves. If you build a query string from user input, you still need to validate the field names and escape values.
How a check flows through a request
Testing a describe check
Test both outcomes. Create a user whose profile or permission set lacks the field, and run the code as that user:
@IsTest
private class AccountRevenueServiceTest {
@IsTest
static void blocksUserWithoutEditAccess() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'revusr',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'revusr' + System.currentTimeMillis() + '@example.com'
);
insert u;
Account acc = new Account(Name = 'Acme');
insert acc;
Boolean blocked = false;
System.runAs(u) {
// Assumes Annual Revenue is read-only for this profile in the test org.
try {
AccountRevenueService.setRevenue(acc.Id, 500);
} catch (AccountRevenueService.AccessException e) {
blocked = true;
}
}
Assert.isTrue(blocked, 'The update should be blocked');
}
}The test only proves something if the user really lacks edit access. Standard profiles often allow editing standard fields, so for a reliable test, use a custom field and a profile or permission set you control. Add a second test for a user who has access and assert the update succeeds.
Summary of when to use each method
Use describe checks when you need per-field decisions, custom errors, or compatibility with code written before user mode existed. Check object permissions and field permissions together, fail closed on unknown names, and cache the describe maps instead of rebuilding them in loops.
Exercise
A method queries Account with dynamic SOQL and adds AnnualRevenue to the field list only when isAccessible() returns true. A later caller reads acc.AnnualRevenue for a user without Read access. What happens, and how would you fix the caller?
Show answer
The caller throws a System.SObjectException because the field was never queried. The security check worked, but the caller assumed the field was present. Fix it by making the caller handle the missing field, for example by wrapping the read in a check such as acc.getPopulatedFieldsAsMap().containsKey('AnnualRevenue') before using the value.
Exercise
Why does Schema.sObjectType.Account.fields.AnnualRevenue.isUpdateable() returning true not guarantee that an update will be allowed?
Show answer
Field access is only one layer. The user may lack the Edit object permission on Account, or the record sharing rules may deny edit access to that specific record. Check object permissions as well, and run the code with sharing enforced.