From 6d29ce9d75debc0a2f0bb4220193e1a12e3ffe82 Mon Sep 17 00:00:00 2001 From: Rick Anderson <3605364+Rick-Anderson@users.noreply.github.com> Date: Mon, 14 Sep 2020 11:45:02 -1000 Subject: [PATCH] Update cross-site-scripting.md (#19857) --- aspnetcore/security/cross-site-scripting.md | 156 +++++++++++--------- 1 file changed, 86 insertions(+), 70 deletions(-) diff --git a/aspnetcore/security/cross-site-scripting.md b/aspnetcore/security/cross-site-scripting.md index f981870fc2..039e6bf9f5 100644 --- a/aspnetcore/security/cross-site-scripting.md +++ b/aspnetcore/security/cross-site-scripting.md @@ -56,84 +56,100 @@ There may be times you want to insert a value into JavaScript to process in your ```cshtml @{ - var untrustedInput = "<\"123\">"; - } + var untrustedInput = ""; +} -
+ - - ``` - -This will produce the following HTML - -```html - - - - ``` - -Which, when it runs, will render the following: - -``` -<"123"> - <"123"> -``` - -You can also call the JavaScript encoder directly: - -```cshtml -@using System.Text.Encodings.Web; - @inject JavaScriptEncoder encoder; - - @{ - var untrustedInput = "<\"123\">"; - } - - -``` - -This will render in the browser as follows: - -```html + ``` + +The preceding markup generates the following HTML: + +```html + + + + + + + ``` + +The preceding code generates the following output: + +``` + + + ``` >[!WARNING] -> Don't concatenate untrusted input in JavaScript to create DOM elements. You should use `createElement()` and assign property values appropriately such as `node.TextContent=`, or use `element.SetAttribute()`/`element[attribute]=` otherwise you expose yourself to DOM-based XSS. +> Do ***NOT*** concatenate untrusted input in JavaScript to create DOM elements or use `document.write()` on data sourced from attributes. +> +> Use one of the following approaches to prevent code from being exposed to DOM-based XSS: +> * `createElement()` and assign property values with appropriate methods or properties such as `node.textContent=` or node.InnerText=`. +> * `document.CreateTextNode()` and append it in the appropriate DOM location. +> * `element.SetAttribute()` +> * `element[attribute]=` ## Accessing encoders in code