liveBook · Manning

Javascript encoding

As explained in ASP.NET Core in Action, 3e

JavaScript encoding is the transformation of data into a representation that is safe to embed in JavaScript source or values.

JavaScript encoding transforms data into a representation safe for embedding in JavaScript values. It helps prevent user-supplied content from becoming executable code during an XSS attack. section 29.1

Use JavaScript encoding when inserting data into JavaScript source:

  • Inject System.Text.Encodings.Web.JavaScriptEncoder and encode the value before placing it inside a script. section 29.1
  • Do not substitute HTML encoding automatically; HTML and JavaScript contexts require different encoders. section 29.1
  • Consider passing values through HTML data attributes and reading them with getAttribute instead of constructing JavaScript source directly. section 29.1

Encoding a name inside a script

Use `@encoder.Encode(name)` when assigning a server-side name to a JavaScript variable: `<script>var name = '@encoder.Encode(name)'</script>`. section 29.1

Figure 29.1 How an XSS vulnerability is exploited. An attacker submits malicious content to your app, which is displayed in the browsers of other users. If the app doesn’t encode the content when writing to the page, the input becomes part of the HTML of the page and can run arbitrary JavaScript.
CH29_F01_Lock3

Trace how malicious submitted content reaches other users’ browsers when output is not encoded. section 29.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Demonstrates encoder usage and contrasts JavaScript with HTML encoding, without detailing encoder internals.
Examples
Uses an encoded JavaScript name, an unsafe script assignment, and an HTML data-attribute alternative.
What it assumes
Assumes basic Razor templates and JavaScript while introducing the distinction between HTML and JavaScript contexts.
What you can do after
Apply it via JavaScriptEncoder when embedding server-side values in JavaScript.
How it connects
Connects JavaScript encoding with XSS attacks, HTML encoding, Razor Pages, and Content-Security-Policy.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.