What is cross-site scripting and how do I protect my ASP.NET application from it?

From Guidance Share

Jump to: navigation, search

J.D. Meier, Prashant Bansode, Alex Mackman


Cross-site scripting (XSS) attacks exploit vulnerabilities in web page validation by injecting client-side script code. This code is then subsequently sent back to an unsuspecting user and executed by the browser. To prevent XSS attacks you need to:

  • Validate Input – Validate any input that is received from outside your application's trust boundary for type, length, format and range. The type and length of the input of the input can be coerced using the RegularExpressionValidator. For range checks, you can use the RangeValidator control to constrain input to a predetermined range
  • Encode Output - If you write text output to a Web page and you do not know with absolute certainty that the text does not contain HTML special characters (such as <, >, and & ), then make sure to pre-process it using the HttpUtility.HtmlEncode method. Do this even if the text came from user input, a database, or a local file. Similarly, use HttpUtility.UrlEncode to encode URL strings.

The HtmlEncode method replaces characters that have special meaning in HTML to HTML variables that represent those characters. For example, < is replaced with &lt and " is replaced with &quot. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.

More Information

For more information on protecting your application from XSS attacks, see “How To: Prevent Cross-site scripting in ASP.NET” at http://msdn.microsoft.com/library/en-us/dnpag2/html/paght000004.asp

Personal tools