1

Is it safe to directly return a SOQL query from a AuraEnabled Apex method like this:

@AuraEnabled(cacheable=true)
public static List<Opportunity> getRecords() {

    return [SELECT ... FROM Opportunity WHERE ...];
}

or should there be some defensive code:

@AuraEnabled(cacheable=true)
public static List<Opportunity> getRecords() {

    List<Opportunity> records = [SELECT ... FROM Opportunity WHERE ...];

    if (records.size() == 0) {
        return new List<Opportunity>(); 
    }
    return records;
}
  • 1
    The former should work without issue. However unless you ensure the fields are appropriately filtered by user permissions, this exposes a security risk. – Phil W Apr 8 at 16:02
  • 1
    The bigger risk is when using dynamic queries that accept string parameters from the page. In these instances you need to be sure to escape single quotes to prevent injection. – gNerb Apr 8 at 16:13
  • 1
    That's certainly a risk if you don't use bindings, but ignoring FLS is also big no-no, at least for partner solutions. – Phil W Apr 8 at 16:22
3

Putting Security.stripInaccessible in the mix addresses most (all?) object and field level filtering, though the class should also be with sharing to make sure row level sharing rules apply:

@AuraEnabled(cacheable=true)
public static List<Opportunity> getRecords() {

    List<Opportunity> opps = [SELECT ... FROM Opportunity WHERE ...];
    return Security.stripInaccessible(AccessType.READABLE, opps).getRecords();
}

There is no need to check for zero rows - just return those - and the query will never return null, just an empty list if there are no rows.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.