認定 Platform デベロッパー資格の更新 (Winter '21) ⇒ 項目レベルとオブジェクトレベルのセキュリティや安全なナビゲーション演算子を使ってみる


ハンズオンの Challenge

Enforce Field and Object Level Security and Use the Safe Navigation Operator in Apex
Simplify your code by using the Security.stripInaccessible method in the Apex class. Also catch any null references using the Safe Navigation operator.

Note: Complete the necessary setup configuration in the Unit text prior to the hands-on challenge section.
Create a new Apex class
Name: ApexSecurityRest
Copy and paste the ApexSecurityRest code provided above.
Use the Security.stripInaccessible method logic to process the results. Remove fields that the user does not have Read access to.
Remove the redundant object- and field-level access checks for Name and Top_Secret. Note: Delete the unneeded code rather than commenting it out.
Apply the Safe Navigation operator functionality to Account in order to avoid null references.

ApexSecurityRest.apxc
@RestResource(urlMapping='/apexSecurityRest')
global with sharing class ApexSecurityRest {
    @HttpGet
    global static Contact doGet() {
        Id recordId = RestContext.request.params.get('id');
        Contact result;
        if (recordId == null) {
           throw new FunctionalException('Id parameter is required');
        }

        List<Contact> results = [SELECT id, Name, Title, Top_Secret__c, Account.Name FROM Contact WHERE Id = :recordId];
        SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.READABLE, results);

        if (!results.isEmpty()) {
            result = results[0];
            if (Schema.sObjectType.Contact.fields.Description.isUpdateable()){
                result.Description = result.Account?.Name;
            }
        }

        return result;
      }
      public class FunctionalException extends Exception{}
      public class SecurityException extends Exception{}
}