# Threat Protection

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Application Security
Source: https://www.devtutorials.ai/learn/blazor/application-security/threat-protection

> Protect a Blazor app from common web threats: XSS and rendering untrusted HTML, CSRF and antiforgery tokens, HTTPS, HSTS and CORS policies, keeping secrets out of WebAssembly, and server-side validation.

## Introduction to Web Threats

- A **threat** is a way someone could harm your app or its users: steal data, act as another user, or break things.
- The person doing it is called an **attacker**. Attacks often come from **input**: text in a form, a link, a request sent by a script.
- A web app is open to everyone on the internet, so you must expect bad input, not only good input.
- The good news: ASP.NET Core and Blazor protect you from many attacks **by default**. This lesson shows what they do and where you must help.

**Real-World Example:**

The Tea Shop lets customers write reviews, place orders and pay. An attacker could hide a script in a review, trick Ravi's browser into sending money, or read a secret key from the app. Each section below closes one of these doors.

## Common Web Threats

| Threat | What the attacker does | Main defence | In this lesson |
|---|---|---|---|
| **XSS** (cross-site scripting) | Puts their own script into your page | Encode output | XSS Protection |
| **CSRF** (cross-site request forgery) | Makes the user's browser send a request they did not want | Antiforgery tokens | CSRF Protection |
| **Eavesdropping** | Reads data travelling over the network | HTTPS and HSTS | Secure Communication |
| **Unwanted cross-site calls** | Calls your API from their own site | CORS policies | Secure Communication |
| **Secret leaks** | Reads keys and passwords from downloaded code | Keep secrets on the server | Protecting Sensitive Data |
| **Tampered requests** | Skips your form and sends any data | Server-side validation | Protecting Sensitive Data |
| **SQL injection** | Puts SQL commands into input | Parameters (EF Core does this) | Database Handling |

<figure className="blz-fig">
<svg viewBox="0 0 640 235" role="img" aria-labelledby="fig-threat-map">
  <title id="fig-threat-map">The Tea Shop in the middle. Around it, six labelled arrows point in: XSS into the page, CSRF into forms, eavesdropping on the network line, cross-site calls into the API, secret leaks out of the WebAssembly download, and tampered requests into the API.</title>
  <defs><marker id="fig-threat-map-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="grn" x="245" y="80" width="150" height="70" rx="14" />
  <text className="t m" x="320" y="112" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Tea Shop</text>
  <text className="t" x="320" y="132" textAnchor="middle" style={{ fontSize: 10 }}>pages, forms, API</text>
  <rect className="org" x="20" y="15" width="150" height="40" rx="10" />
  <text className="t m" x="95" y="40" textAnchor="middle" style={{ fontSize: 11 }}>XSS</text>
  <rect className="org" x="245" y="5" width="150" height="40" rx="10" />
  <text className="t m" x="320" y="30" textAnchor="middle" style={{ fontSize: 11 }}>CSRF</text>
  <rect className="org" x="470" y="15" width="150" height="40" rx="10" />
  <text className="t m" x="545" y="40" textAnchor="middle" style={{ fontSize: 11 }}>Eavesdropping</text>
  <rect className="org" x="20" y="175" width="150" height="40" rx="10" />
  <text className="t m" x="95" y="200" textAnchor="middle" style={{ fontSize: 11 }}>Cross-site calls</text>
  <rect className="org" x="245" y="185" width="150" height="40" rx="10" />
  <text className="t m" x="320" y="210" textAnchor="middle" style={{ fontSize: 11 }}>Secret leaks</text>
  <rect className="org" x="470" y="175" width="150" height="40" rx="10" />
  <text className="t m" x="545" y="200" textAnchor="middle" style={{ fontSize: 11 }}>Tampered requests</text>
  <path className="line" d="M170 45 L241 90" markerEnd="url(#fig-threat-map-a)" />
  <path className="line" d="M320 45 V76" markerEnd="url(#fig-threat-map-a)" />
  <path className="line" d="M470 45 L399 90" markerEnd="url(#fig-threat-map-a)" />
  <path className="line" d="M170 185 L241 140" markerEnd="url(#fig-threat-map-a)" />
  <path className="line" d="M320 150 V181" markerEnd="url(#fig-threat-map-a)" />
  <path className="line" d="M470 185 L399 140" markerEnd="url(#fig-threat-map-a)" />
</svg>
<figcaption>Six ways in. This lesson shows the defence for each.</figcaption>
</figure>

## XSS Protection

### How XSS Attacks Work

- **XSS** (cross-site scripting) means an attacker gets **their own JavaScript** to run inside **your** page.
- It usually starts with input that your page shows later, like a review: `Great tea! <script>...</script>`.
- If the page puts that text into the HTML **as HTML**, every visitor's browser runs the script. It can read what the user sees, send requests as them, or change the page.

<figure className="blz-fig">
<svg viewBox="0 0 640 195" role="img" aria-labelledby="fig-xss">
  <title id="fig-xss">Animation: 1. The attacker posts a review that contains a script. 2. The server saves it. 3. Ravi opens the reviews page, and the script comes with it. 4. In Ravi’s browser, the script runs and sends his data to the attacker.</title>
  <defs><marker id="fig-xss-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="org" x="10" y="20" width="130" height="60" rx="10" />
  <text className="t m" x="75" y="46" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Attacker</text>
  <text className="t" x="75" y="64" textAnchor="middle" style={{ fontSize: 10 }}>review + script</text>
  <rect className="pur" x="255" y="20" width="130" height="60" rx="10" />
  <text className="t m" x="320" y="46" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Server</text>
  <text className="t" x="320" y="64" textAnchor="middle" style={{ fontSize: 10 }}>saves the review</text>
  <rect className="blu" x="500" y="20" width="130" height="60" rx="10" />
  <text className="t m" x="565" y="46" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Ravi</text>
  <text className="t" x="565" y="64" textAnchor="middle" style={{ fontSize: 10 }}>opens reviews</text>
  <rect className="org" x="440" y="130" width="190" height="50" rx="10" />
  <text className="t m" x="535" y="160" textAnchor="middle" style={{ fontSize: 11 }}>script runs as Ravi</text>
  <path className="line" d="M140 50 H251" markerEnd="url(#fig-xss-a)" />
  <path className="line" d="M385 50 H496" markerEnd="url(#fig-xss-a)" />
  <path className="line" d="M565 80 V126" markerEnd="url(#fig-xss-a)" />
  <path className="line" d="M440 155 H144 V84" markerEnd="url(#fig-xss-a)" />
  <text className="t" x="290" y="148" textAnchor="middle" style={{ fontSize: 10 }}>Ravi's data goes to the attacker</text>
  <circle r="7" style={{ fill: "#dc2626" }}>
    <animate attributeName="cx" values="140;320;565;565;440;75" keyTimes="0;0.2;0.45;0.6;0.75;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="50;50;50;155;155;84" keyTimes="0;0.2;0.45;0.6;0.75;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>One bad review becomes a script in every visitor’s browser.</figcaption>
</figure>

**Blazor protects you by default.** `@review` writes text, not HTML. Characters like `<` become **encoded** (written as `&lt;`), so the browser shows them as letters and never runs them.

The danger is **`MarkupString`**: `@((MarkupString)review)` tells Blazor "this is trusted HTML, insert it as it is".

In the below example, the same review is shown twice. The encoded line is safe. The `MarkupString` line runs the attacker's code. (Here it only adds a red line, but it could do anything the user can do.)

<div>@review</div>

<h4>Unsafe: (MarkupString)review</h4>
<div>@((MarkupString)review)</div>

@code {
      // A review typed by an attacker
      private string review = @"<b>Great tea!</b><img src=""x"" onerror=""this.parentElement.insertAdjacentHTML('beforeend', '<p style=color:red>Script ran! It could steal your data.</p>')"">";
}
`,
  }}
/>

- The safe line shows the raw characters, `<b>` and all. Nothing runs.
- The unsafe line makes `Great tea!` bold, **and** runs the hidden `onerror` script.

### Rendering Untrusted HTML

Sometimes you **want** some formatting from users, like bold text or line breaks. Never cast their text straight to `MarkupString`. Choose one of these:

| Way | How | When |
|---|---|---|
| **Encode, then add your own tags** | Encode the text, then turn safe markers (like a new line) into your own HTML | Simple formatting |
| **Sanitize** | An HTML sanitizer removes every tag and attribute that is not on a safe list | Rich text from an editor |
| **Use a format, not HTML** | Let users write Markdown, and convert it with a library that sanitizes | Comments, posts |

In the below example, the review is **encoded first** with `HtmlEncoder`, and only then are new lines turned into `<br>`. The attacker's tags arrive as harmless text.

<div style="border: 1px solid #ccc; padding: 8px">
      @((MarkupString)SafeHtml(review))
</div>

@code {
      private string review = "Lovely chai!\\nSecond line.\\n<img src=x onerror=alert(1)>";

      private static string SafeHtml(string text)
      {
          // 1. Encode everything the user typed: < becomes &lt; and so on
          var encoded = HtmlEncoder.Default.Encode(text);

          // 2. Only now add our own, known-safe HTML
          return encoded.Replace("&#xA;", "<br>");
      }
}
`,
  }}
/>

- Type more text with tags in the box and click outside it. Only the line breaks become HTML.
- For rich text, use a tested sanitizer library, such as the **HtmlSanitizer** NuGet package:

string safeHtml = sanitizer.Sanitize(review); // removes <script>, onerror=..., javascript: links
`}
/>

Treat every `MarkupString` as a warning sign. Only use it for HTML you made yourself, or HTML that went through an encoder or sanitizer.

## CSRF Protection

### How CSRF Attacks Work

- Remember from **Authentication**: after login, the browser sends the login cookie with **every** request to that site, by itself.
- **CSRF** (cross-site request forgery) abuses this. An attacker's page contains a hidden form that posts to **your** site.
- When a logged-in user opens the attacker's page, their browser sends the form **with the user's cookie**. Your server sees a valid login and does what the form asks: change the email, place an order, send money.
- The user never clicked anything on your site.

<figure className="blz-fig">
<svg viewBox="0 0 640 165" role="img" aria-labelledby="fig-csrf">
  <title id="fig-csrf">Animation: Ravi is logged in to the Tea Shop. He opens cheap-prizes.example. A hidden form there posts to teashop.com/transfer. The browser adds Ravi’s cookie by itself, so without a token check the shop accepts the request.</title>
  <defs><marker id="fig-csrf-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="60" width="150" height="90" rx="12" />
  <text className="t m" x="85" y="90" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Ravi's browser</text>
  <text className="t" x="85" y="110" textAnchor="middle" style={{ fontSize: 10 }}>has the shop cookie</text>
  <text className="t" x="85" y="128" textAnchor="middle" style={{ fontSize: 10 }}>opens a prize page</text>
  <rect className="org" x="245" y="10" width="160" height="60" rx="12" />
  <text className="t m" x="325" y="36" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>cheap-prizes.example</text>
  <text className="t" x="325" y="54" textAnchor="middle" style={{ fontSize: 10 }}>hidden form</text>
  <rect className="pur" x="480" y="60" width="150" height="90" rx="12" />
  <text className="t m" x="555" y="90" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>teashop.com</text>
  <text className="t" x="555" y="110" textAnchor="middle" style={{ fontSize: 10 }}>POST /transfer</text>
  <text className="t" x="555" y="128" textAnchor="middle" style={{ fontSize: 10 }}>cookie is valid...</text>
  <path className="line" d="M160 75 L241 45" markerEnd="url(#fig-csrf-a)" />
  <path className="line" d="M160 125 H476" markerEnd="url(#fig-csrf-a)" />
  <text className="t m" x="320" y="118" textAnchor="middle" style={{ fontSize: 11 }}>form post + Ravi's cookie (sent by itself)</text>
  <circle r="7" style={{ fill: "#dc2626" }}>
    <animate attributeName="cx" values="160;245;245;160;476" keyTimes="0;0.25;0.35;0.55;1" dur="5s" repeatCount="indefinite" />
    <animate attributeName="cy" values="75;45;45;125;125" keyTimes="0;0.25;0.35;0.55;1" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>The attacker cannot read Ravi’s cookie, but they can make his browser send it.</figcaption>
</figure>

### Antiforgery Tokens (UseAntiforgery)

- The fix is an **antiforgery token**: a secret random value that the server puts into **its own** forms.
- When a form is posted, the server checks the token. A form on the attacker's site cannot know the token, so its post is rejected with **400 Bad Request**.
- In a Blazor Web App this is **on by default**:
  - `AddRazorComponents()` registers the antiforgery services.
  - `app.UseAntiforgery()` in `Program.cs` checks the token on every form post.
  - `<EditForm>` adds the token to the form by itself.
  - A plain HTML `<form method="post">` needs **`<AntiforgeryToken />`** inside it, like the template's Logout form (see **Authentication**).

      <button type="submit">Save</button>
</form>

@code {
      [SupplyParameterFromForm]
      private string? Email { get; set; }

      private void Save()
      {
          // Runs only when the token was valid
      }
}
`}
/>

In the below example, `FakeBankServer` plays the bank. Both forms reach it **with Ravi's login cookie**. Only the bank's own form knows the token. Try both, then untick **Check antiforgery tokens** and try the evil form again.

<p><button @onclick="RealForm">Real form on teashop.com (has the token)</button></p>
<p><button @onclick="EvilForm">Hidden form on cheap-prizes.example (no token)</button></p>

<p>Server says: @result</p>
<p>Ravi's balance: @server.Balance</p>

@code {
      private FakeBankServer server = new();
      private string result = "";

      // The shop's own page put the token into its form
      private void RealForm() => result = server.Post("Meena", 100, server.FormToken);

      // The attacker's page cannot know the token
      private void EvilForm() => result = server.Post("Attacker", 900, null);
}
`,
    "Services/FakeBankServer.cs": `namespace BlazorApp.Services;

// A pretend bank server, so the box can show what antiforgery tokens do.
public class FakeBankServer
{
      // The secret token the bank puts in its own forms (UseAntiforgery does this for you)
      public string FormToken { get; } = Guid.NewGuid().ToString("N")[..8];
      public int Balance { get; private set; } = 1000;
      public bool CheckTokens { get; set; } = true;

      // The browser sends Ravi's login cookie with EVERY request to the bank,
      // even when the form is on another site. So the cookie alone proves nothing.
      public string Post(string toAccount, int amount, string? token)
      {
          if (CheckTokens && token != FormToken)
          {
              return "400 Bad Request: missing or wrong antiforgery token";
          }
          Balance -= amount;
          return "200 OK: sent " + amount + " to " + toAccount;
      }
}
`,
  }}
/>

- With the check on, the evil form gets **400** and the balance stays the same.
- With the check off, the same post **succeeds**: that is a CSRF attack.

`SameSite=Lax` cookies (see **Authentication**) also stop most cross-site posts. Antiforgery tokens are the second lock. Keep both.

## Secure Communication

### HTTPS and HSTS

- Plain **HTTP** sends everything as readable text. Anyone on the same network (for example, café Wi-Fi) can read or change it: passwords, cookies, orders. This is **eavesdropping**.
- **HTTPS** encrypts the connection with **TLS** (a security protocol), using the site's **certificate**: a file that proves the site is really `teashop.com`. The browser shows a padlock.
- **`UseHttpsRedirection()`** sends `http://` visitors to `https://` (see **Middleware Pipeline**).
- But that first `http://` request still travels unencrypted. **HSTS** (HTTP Strict Transport Security) fixes this: the header `Strict-Transport-Security` tells the browser "**only** use HTTPS for this site from now on". **`UseHsts()`** adds it.

<figure className="blz-fig">
<svg viewBox="0 0 640 240" role="img" aria-labelledby="fig-https">
  <title id="fig-https">Two lanes. HTTP: the message password=chai123 travels as readable text, and an eavesdropper in the middle reads it. HTTPS: the same message travels as scrambled text, x9#Lq..., and the eavesdropper sees only noise.</title>
  <defs><marker id="fig-https-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="20" width="100" height="50" rx="10" />
  <text className="t m" x="60" y="50" textAnchor="middle" style={{ fontSize: 12 }}>Browser</text>
  <rect className="pur" x="530" y="20" width="100" height="50" rx="10" />
  <text className="t m" x="580" y="50" textAnchor="middle" style={{ fontSize: 12 }}>Server</text>
  <path className="line" d="M110 45 H526" markerEnd="url(#fig-https-a)" />
  <text className="t m" x="200" y="37" textAnchor="middle" style={{ fontSize: 11 }}>HTTP: password=chai123</text>
  <rect className="org" x="370" y="78" width="110" height="34" rx="8" />
  <text className="t" x="425" y="99" textAnchor="middle" style={{ fontSize: 10 }}>eavesdropper reads it</text>
  <path className="line" d="M425 78 V52" />
  <rect className="blu" x="10" y="140" width="100" height="50" rx="10" />
  <text className="t m" x="60" y="170" textAnchor="middle" style={{ fontSize: 12 }}>Browser</text>
  <rect className="pur" x="530" y="140" width="100" height="50" rx="10" />
  <text className="t m" x="580" y="170" textAnchor="middle" style={{ fontSize: 12 }}>Server</text>
  <path className="line" d="M110 165 H526" markerEnd="url(#fig-https-a)" />
  <text className="t m" x="200" y="157" textAnchor="middle" style={{ fontSize: 11 }}>HTTPS: x9#Lq!7pZ...</text>
  <rect className="grn" x="370" y="198" width="110" height="34" rx="8" />
  <text className="t" x="425" y="219" textAnchor="middle" style={{ fontSize: 10 }}>sees only noise</text>
  <path className="line" d="M425 198 V172" />
</svg>
<figcaption>HTTPS turns readable data into noise for anyone in the middle.</figcaption>
</figure>

- `UseHsts()` is skipped in Development, because a browser remembers HSTS for a long time and `localhost` is used by many projects.
- On your computer, the .NET SDK gives you a **development certificate**. Trust it once:

### CORS Policies

- An **origin** is the scheme, host and port of a page: `https://teashop.com` and `https://localhost:7001` are different origins.
- For safety, a browser does **not** let a page read answers from another origin's API. This is the **same-origin policy**.
- **CORS** (cross-origin resource sharing) lets the **API** say which other origins may read its answers, with the header **`Access-Control-Allow-Origin`**.
- You need it when your Blazor WebAssembly app and your API run on different addresses (see **API Integration**).
- The **browser** enforces CORS. Tools like `curl` or other servers ignore it, so CORS is **not** a login check. Still use `[Authorize]` (see **Authorization**).

      options.AddPolicy("BlazorClient", policy =>
          policy.WithOrigins("https://localhost:7001", "https://teashop.com")   // exact origins only
                .AllowAnyHeader()
                .AllowAnyMethod()));

var app = builder.Build();

app.UseCors("BlazorClient");   // before the endpoints
app.MapControllers();
`}
/>

In the below example, `FakeApiServer` allows only `https://teashop.com`. `FakeBrowser` does what a real browser does: it reads the answer only when the header matches the page's origin.

<button @onclick='() => Call("https://admin.teashop.com")'>Page on https://admin.teashop.com</button>
<button @onclick='() => Call("https://evil.example")'>Page on https://evil.example</button>

<p>@result</p>

@code {
      private FakeApiServer api = new();
      private string result = "";

      private void Call(string pageOrigin) => result = FakeBrowser.Fetch(api, pageOrigin);
}
`,
    "Services/FakeApiServer.cs": `namespace BlazorApp.Services;

// A pretend API server and browser, so the box can show how CORS works.
public class FakeApiServer
{
      // Like policy.WithOrigins(...) in the API's Program.cs
      public List<string> AllowedOrigins { get; } = new() { "https://teashop.com" };

      // The server answers every request, and adds the CORS header only for allowed origins
      public (string Body, string? AllowOrigin) Get(string origin) =>
          ("Masala, Ginger", AllowedOrigins.Contains(origin) ? origin : null);
}

public static class FakeBrowser
{
      // The browser, not the server, decides whether the page may read the answer
      public static string Fetch(FakeApiServer api, string pageOrigin)
      {
          var (body, allowOrigin) = api.Get(pageOrigin);
          return allowOrigin == pageOrigin
              ? "Allowed. The page reads: " + body
              : "Blocked by CORS: the answer has no Access-Control-Allow-Origin for " + pageOrigin;
      }
}
`,
  }}
/>

- Even `admin.teashop.com` is blocked: a different host is a different origin. Add it to `AllowedOrigins` to allow it.
- Never use `AllowAnyOrigin()` on an API that uses login cookies or tokens. List the exact origins.

## Protecting Sensitive Data

### Keeping Secrets Out of WebAssembly

- With **WebAssembly** (see **WebAssembly & Auto**), your app's DLL files are **downloaded to the browser**. Anyone can save them and read them with a free tool (a decompiler).
- So everything inside a WebAssembly project is **public**: your code, your constants, and `wwwroot/appsettings.json`.
- A **secret** is anything that gives power: an API key, a database connection string, a payment key, a password. Secrets must **never** be in WebAssembly code.

<figure className="blz-fig">
<svg viewBox="0 0 640 190" role="img" aria-labelledby="fig-wasm-secret">
  <title id="fig-wasm-secret">Animation: the server sends TeaShop.Client.dll to the browser. Inside the DLL is ApiKey = sk_live_.... A magnifying glass in the browser reads the key out of the file.</title>
  <defs><marker id="fig-wasm-secret-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="10" y="50" width="150" height="90" rx="12" />
  <text className="t m" x="85" y="88" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Server</text>
  <text className="t" x="85" y="108" textAnchor="middle" style={{ fontSize: 10 }}>sends the app</text>
  <rect className="blu" x="460" y="30" width="170" height="130" rx="12" />
  <text className="t m" x="545" y="54" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Anyone's browser</text>
  <rect className="org" x="480" y="70" width="130" height="70" rx="8" />
  <text className="t m" x="545" y="94" textAnchor="middle" style={{ fontSize: 10 }}>TeaShop.Client.dll</text>
  <text className="t" x="545" y="116" textAnchor="middle" style={{ fontSize: 10 }}>ApiKey = sk_live_...</text>
  <path className="line" d="M160 95 H456" markerEnd="url(#fig-wasm-secret-a)" />
  <text className="t m" x="308" y="87" textAnchor="middle" style={{ fontSize: 11 }}>download</text>
  <rect className="box" x="230" y="104" width="130" height="24" rx="6"><animate attributeName="x" values="160;330;330" keyTimes="0;0.6;1" dur="4s" repeatCount="indefinite" /></rect>
  <text className="t" x="295" y="121" textAnchor="middle" style={{ fontSize: 10 }}>.dll file<animate attributeName="x" values="225;395;395" keyTimes="0;0.6;1" dur="4s" repeatCount="indefinite" /></text>
</svg>
<figcaption>Whatever is inside a WebAssembly DLL, the user has it too.</figcaption>
</figure>

In the below example, a `PaymentSettings` class holds a "secret" key. The page then does what any curious user could do: it opens the app's own DLL and lists every constant in it.

<ul>
      @foreach (var line in found)
      {
          <li>@line</li>
      }
</ul>

@code {
      private List<string> found = new();

      private void LookInside()
      {
          found.Clear();
          var dll = typeof(PaymentSettings).Assembly;   // the app's own code file
          foreach (var type in dll.GetTypes())
          {
              foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
              {
                  if (field.IsLiteral)   // a const
                  {
                      found.Add(type.Name + "." + field.Name + " = " + field.GetRawConstantValue());
                  }
              }
          }
      }
}
`,
    "Settings/PaymentSettings.cs": `namespace BlazorApp.Settings;

public static class PaymentSettings
{
      // NEVER do this in WebAssembly: this file is downloaded by every visitor
      private const string ApiKey = "sk_live_TEA-12345-SECRET";
      public const string ApiUrl = "https://pay.example.com";
}
`,
  }}
/>

- Even the **private** key is found. `private` only hides it from other C# code, not from people.

Where secrets belong instead:

| Do | Don't |
|---|---|
| Keep the secret on the **server** (Blazor Server code or your Web API) | Put it in WebAssembly code or `wwwroot` |
| Let the WebAssembly app call **your** API, and the API calls the payment service with the key | Call the payment service from the browser with the key |
| During development, use **User Secrets** (`dotnet user-secrets`) | Put real keys in `appsettings.json` in Git |
| In production, use environment variables or a key vault | Commit `.env` files with keys |

A quick test for any value in a WebAssembly app: "Would it be OK if a visitor read this?" If the answer is no, it belongs on the server.

{
      // Call the payment service here, with paymentKey. The browser never sees the key.
      return Results.Ok();
}).RequireAuthorization();
`}
/>

### Server-Side Validation

- In **Form Validation**, `<DataAnnotationsValidator>` checked the form **in the browser**. That gives quick, friendly messages.
- But an attacker does not have to use your form. They can send **any** request to your API with a tool or a script: a quantity of `-50`, a price of `0`, a missing name.
- So the **server must check everything again**, and must never trust values like prices from the client.
- Put the rules (`[Required]`, `[Range]`) on a model **shared** by the form and the API. Then both sides check the same rules.

      Results.Created("/api/orders/1", order));
// Quantity = -50  →  400 Bad Request:
// {"errors":{"Quantity":["The field Quantity must be between 1 and 20."]}}
`}
/>

- Controllers with `[ApiController]` (see **API Integration**) check the attributes by themselves and answer **400**.
- In Blazor Server components, the form's code already runs on the server. Still check `EditContext.Validate()` or the rules again before you save.

In the below example, the form validates in the browser. The **Send a tampered request** button skips the form, like an attacker would, and sends a quantity of `-50` straight to the API. The server's own check stops it.

          <option>Masala</option>
          <option>Ginger</option>
      <button type="submit">Order</button>
      <ValidationMessage For="() => order.Quantity" />

<button @onclick="SendTampered">Send a tampered request</button>

<p>Server says: @result</p>

@code {
      private OrderRequest order = new();
      private FakeOrderApi api = new();
      private string result = "";

      private void Send() => result = api.Post(order);

      // An attacker skips the form and its checks
      private void SendTampered() =>
          result = api.Post(new OrderRequest { Tea = "Masala", Quantity = -50 });
}
`,
    "Models/OrderRequest.cs": `namespace BlazorApp.Models;

using System.ComponentModel.DataAnnotations;

// Shared by the form (client) and the API (server)
public class OrderRequest
{
      [Required]
      public string Tea { get; set; } = "Masala";

      [Range(1, 20, ErrorMessage = "Quantity must be between 1 and 20.")]
      public int Quantity { get; set; } = 1;
}
`,
    "Services/FakeOrderApi.cs": `namespace BlazorApp.Services;

using System.ComponentModel.DataAnnotations;
using BlazorApp.Models;

// A pretend order API. The real one runs on the server (see API Integration).
public class FakeOrderApi
{
      // Prices live on the server. The client never sends a price.
      private readonly Dictionary<string, int> prices = new() { ["Masala"] = 30, ["Ginger"] = 25 };

      public string Post(OrderRequest order)
      {
          // Check the rules again, here on the server
          var errors = new List<ValidationResult>();
          if (!Validator.TryValidateObject(order, new ValidationContext(order), errors, true))
          {
              return "400 Bad Request: " + string.Join(" ", errors.Select(e => e.ErrorMessage));
          }
          if (!prices.TryGetValue(order.Tea, out var price))
          {
              return "400 Bad Request: unknown tea";
          }
          return "201 Created: " + order.Quantity + " x " + order.Tea + " = Rs " + order.Quantity * price;
      }
}
`,
  }}
/>

- Type `-5` in the form and click **Order**: the browser check stops it.
- **Send a tampered request** never touches the form, yet the server answers **400** because it checks `[Range]` itself.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `@((MarkupString)userText)` | Blazor makes all HTML safe | Show user text with `@userText`, or sanitize it first | XSS: the attacker's script runs for every visitor |
| A plain `<form method="post">` without `<AntiforgeryToken />` | Forms are protected by themselves | Use `<EditForm>`, or add `<AntiforgeryToken />` | 400 Bad Request, or no protection if checks are turned off |
| Removing `UseAntiforgery()` or adding `.DisableAntiforgery()` | Tokens only get in the way | Keep the check for every form post | CSRF attacks succeed |
| `AllowAnyOrigin()` on a private API | CORS is just a nuisance | List the exact origins with `WithOrigins(...)` | Any site may read your users' data |
| An API key in WebAssembly code or `wwwroot/appsettings.json` | `private` or compiled code hides it | Keep secrets on the server; use User Secrets in development | Anyone can download and use the key |
| Only validating in the browser | The form is the only way in | Validate again on the server; compute prices there | Negative quantities, free orders, bad data |

</div>

## Check Yourself

## Exercises

## What to Remember

- Expect bad input. Blazor and ASP.NET Core block many attacks by default; know where you must help.
- **XSS**: `@text` is encoded and safe. Use `MarkupString` only for HTML you made, encoded or sanitized.
- **CSRF**: the browser sends cookies by itself, so forms need an **antiforgery token**. `AddRazorComponents` and `UseAntiforgery()` check it; `<EditForm>` adds it; plain forms need `<AntiforgeryToken />`.
- **HTTPS** encrypts traffic. `UseHttpsRedirection()` moves users to HTTPS, and `UseHsts()` makes browsers stay there.
- **CORS** lets an API name the exact origins whose pages may read its answers. The browser enforces it; it is not a login check.
- Everything in **WebAssembly** is public. Keep secrets on the server (User Secrets in development).
- **Validate on the server** too, and compute important values like prices there.

Next: **Capstone Project - Tea Shop**
