1

I have followed this official guide: SOQL Injection and came up with this:

String query = 'Select FirstName, LastName, Phone, Email From Contact Where ';
if(String.isNotBlank(fName)) {
        firstName = '%'+fName+'%';
        if(String.isNotBlank(lName)) {
            lastName = '%'+lName+'%';
            query += 'FirstName LIKE :firstName AND LastName LIKE :lastName';
        } else {
            query += 'FirstName LIKE :firstName';
        }
    } else {
        if(String.isNotBlank(lName)) {
            lastName = '%'+lName+'%';
            query += 'LastName LIKE :lastName';
        }
    }

And this works perfect. But as I am performing a Contact search, I would like to have a perfect search result. So, I have replaced LIKE with = symbol. And then, my query is always of contactList.size() = 0. I am not sure what I am missing here. Can someone please shed some light here?

1 Answer 1

3

You don't need to use % signs to defend against SOQL injection: your use of Apex binds does that for you. By binding the variable value, you let the runtime take responsibility for escaping any special characters in the user input which might - if interpreted as part of the query itself - produce unexpected behavior or information disclosure.

If you're not intending to perform a wildcarded search, remove

    firstName = '%'+fName+'%';
    lastName = '%'+lName+'%';

and use = instead of LIKE. Your code will still be safe from SOQL injection. The use of wildcards and LIKE searches in the linked documentation is to create a demonstration vulnerability that can be mitigated through this technique.

Adding wildcards without LIKE will have the result of searching for a literal string with % signs in it, which you don't want.

1
  • Wow!! I've learned something new. I didn't know that % would be considered as a literal string if I am using = symbol. Now that make perfect sense, why my list is always empty. Commented Nov 5, 2019 at 21:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .