A developer has a Apex controller for a Visualforce page that takes an ID as a URL parameter. How should the developer prevent a cross site scripting vulnerability?
Correct Answer: C
Cross site scripting (XSS) is a vulnerability that occurs when an attacker can insert unauthorized HTML or JavaScript code into a web page viewed by other users. This can lead to hijacking the user's session, stealing confidential information, or defacing the page. To prevent XSS, the developer should always validate and encode any user-supplied data before displaying it on the page. The ApexPages.currentPage() .getParameters()
.get('url_param') method returns the value of the URL parameter as a string, but does not perform any validation or encoding. Therefore, it is vulnerable to XSS if the parameter contains malicious code. The ApexPages.currentPage() .getParameters() .get('url_param') .escapeHtml4() method escapes the HTML characters in the parameter value, such as <, >, &, and ", but does not prevent JavaScript code from being executed. Therefore, it is also vulnerable to XSS if the parameter contains a script tag or an event handler attribute. The String.escapeSingleQuotes(ApexPages.currentPage() .getParameters(). get('url_param')) method escapes the single quotes in the parameter value, but does not affect any other characters. Therefore, it is also vulnerable to XSS if the parameter contains any HTML or JavaScript code. The String.ValueOf(ApexPages.currentPage() .getParameters() .get('url_param')) method converts the parameter value to a string and encodes any HTML characters as HTML entities, such as <, >, &, and ". This prevents any HTML or JavaScript code from being rendered or executed on the page. Therefore, it is the best option to prevent XSS. References: You can learn more about XSS and how to prevent it in Apex from the following sources:
* Cross Site Scripting (XSS) | Apex Developer Guide
* Secure Coding Cross Site Scripting | Secure Coding Guide
* Cross-Site Scripting in Apex | SecureFlag Security Knowledge Base
Recent Comments (The most recent comments are at the top.)
the correct answer is B :
uses the escapeHtml4() method, which is specifically designed to escape characters that could be used in cross-site scripting attacks by converting them to their HTML entity equivalents. This method helps to neutralize potential XSS vectors by ensuring that characters like " <, >, &" and others are rendered harmless in HTML contexts.