Cross-site scripting (XSS) and output encoding

If a page prints user input as HTML, that input can run as script in other users’ browsers. Encoding output stops it.

Time O(1)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

XSS happens when untrusted text is placed into a page in a way the browser treats as markup or script. Stored XSS saves it (a comment); reflected XSS bounces it from the URL. Context-aware output encoding turns special characters like < and > into harmless entities, so the browser shows them instead of running them.

Code

// Vulnerable: raw HTML from the user goes into the page
html += "<p>" + comment.Text + "</p>";
// Safe: encode for the HTML context before output
html += "<p>" + HtmlEncoder.Default.Encode(comment.Text) + "</p>";
// Razor encodes @comment.Text automatically
// Extra layers: Content-Security-Policy, HttpOnly cookies

Tips

In the .NET library

Razor views encode @expressions; Html.Raw turns that off, so treat every Html.Raw as a review flag.