How to avoid security risks with escape=”False” in output tags

Ok, say for example the output we need on the page must include HTML tags and we want to avoid any security risks…..

Scenerio 1: No user input, string is completely generated by apex code and displayed by the page. – Is there any risk, if so what is the best way to avoid

Scenerio 2: String is constructed in a way that user input is added to the string. The input has string.escapeSingleQuotes() AND .escapeHTML4() applied. – The obvious risks are Injection and XSS but those would appear to be negated by the applied methods. What if any additional risks are present?

Keep in mind that the application needs the output of the string to contain the HTML elements the apex code adds so it will not be an option to set escape="true"

This question is both a learning question and a best practice question as this is one of the most frequent reasons apps fail security review.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

For the first scenario, there’s no risk, because the code being emitted is directly created by the developer and is under the developer’s full control. There’s no risk of malicious injection, so there’s no security risk.

For the second scenario, you should escape the content that’s not under your control. For example, you might do this:

output += String.format('<td>{0}</td>', new String[] { userInput.escapeHtml4(); });

The intent is to make a cell (td) with whatever user content they desire. By escaping the input so that greater-than, less-than, ampersand, quote, and apostrophe are replaced with HTML entities, you guarantee that no script injection can occur, malforming the page or even executing arbitrary JavaScript.

escapeSingleQuotes is for SOQL, and should not be used for escaping HTML. It won’t cause any security problem, but it would cause extra apostrophes to appear in the output. Other than that, there’s no other risks that you’d run into, since escaping the four main character entities that would be used for XSS will eliminate any known security risk.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x