When a route answers with Results.Content(text, "text/html; charset=utf-8"), the browser reads the text as a web page: HTML. If that page repeats something a user typed, and they typed <script>alert(1)</script>, the browser runs that script on your site, as whoever is looking at the page. This attack is called XSS (cross-site scripting).
The fix is to escape what you echo. WebUtility.HtmlEncode, from System.Net, turns < into < and > into >. The browser shows those codes as the characters, and never runs them. For example, on a greeting route:
app.MapGet("/hello", (HttpRequest request) => {
var name = request.Query["name"].ToString();
return Results.Content("Hello, " + WebUtility.HtmlEncode(name) + "!", "text/html; charset=utf-8");
});
Here WebUtility.HtmlEncode("<b>Mia</b>") gives <b>Mia</b>: the visitor sees the tags as text, not a bold name. JSON answers (Results.Json) don't need this, because a browser never runs a JSON answer as a page.
Your code must answer these requests. A user signed up with the email <script>alert(1)</script>@evil.com, and an admin added a product named <i>Desk</i>:
GET /welcome (Authorization: Bearer <token>) → 200 Welcome back, <script>alert(1)</script>@evil.com! GET /search?q=ot → 200 Products matching ot: Notebook, Teapot GET /search?q=sofa → 200 No products match sofa GET /search?q=<script>alert(1)</script> → 200 No products match <script>alert(1)</script> GET /search?q=desk → 200 Products matching desk: <i>Desk</i>
Your task: make /welcome answer HTML with the email encoded. Then build GET /search: read q from the query string, find the products whose name contains it, and answer the no-match text or the names found, as HTML, with q and the names encoded.
Assignment
Follow the Coding Tutorial to encode the email in /welcome and to build a safe /search page.
Hint
Read the words with request.Query["q"].ToString() and give the query "%" + q + "%" as its $pattern value. You can join WebUtility.HtmlEncode(…) to normal text with +: put every part that doesn't come from your own code inside it.
Free plan: 30 tutor messages. PRO is unlimited.
