Prefer sanitizing output instead of input to prevent XSS Attacks.
Problem with Input Sanitization:
Encoders might go pretty aggressive and change the original input. So, if your email id contains @
, it might get converted to @
changing the whole meaning of the input and break the functionality.
Input Validation:
Input validation is very important for data integrity. For example, check if it's a valid email before saving it to database. This kind of validation will inherently prevent attackers from saving script data inside your database (1st half of xss attack). But, some input fields are very open by it's nature, for example: comment box, or html editor. These inputs can't be validated.
Output Sanitization:
Having html scripts inside your database is not the prime reason for xss attacks, but getting them executed while rendering in html causes the issue. So, in the context of XSS, always encode your output with encoder like ESAPI.encodeForHTML()
, input validation is optional, and good to have for many reasons.
XSS and SPA (Angular/React)
If your UI is a Single Page Application using technologies like Angular, React. Then you might not need to encode your output from BE. As, these technologies will make sure to render scripts(if any) as plain text, instead of executing them.