A3 – Preventing cross-site scripting
Cross-site scripting, as seen previously, happens when the data shown to the user is not correctly encoded and the browser interprets it as a script code and executes it. This also has an input validation factor, as a malicious code is usually inserted through input variables.
In this recipe, we will cover the input validation and output encoding required for developers to prevent XSS vulnerabilities in their applications.
How to do it...
The first sign of an application being vulnerable to XSS is that in the page it reflects the exact input given by the user. So, try not to use user-given information to build output text.
When you need to put user-provided data in the output page, validate such data to prevent the insertion of any type of code. We already saw how to do that in the A1 – Preventing injection attacks recipe.
If, for some reason, the user is allowed to input special characters or code fragments, sanitize or properly encode the text before inserting...