Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 52 ยท Authentication and Authorization

Web Security Essentials

The web security basics every ASP.NET Core developer needs: HTTPS and HSTS, security headers, XSS encoding, antiforgery tokens, injection, data protection and open redirects.

Authentication and authorization decide who may do what, but they only help if the rest of the application does not hand attackers a way around them. Most successful attacks on web apps are not clever cryptography breaks: they are ordinary mistakes such as printing user input into a page unescaped, gluing it into a SQL string, or trusting a redirect address from the query string. The good news is that ASP.NET Core's defaults prevent many of them, as long as you know which defaults you rely on and which ones you must switch on.

This lesson walks through the essentials: transport security (HTTPS and HSTS), response headers, cross-site scripting, cross-site request forgery, injection, the Data Protection API and open redirects. Each topic has a running example where the framework can show it.

A quick map of the threats

flowchart LR
    U["Browser"] -->|"1. HTTPS + HSTS<br/>(no eavesdropping)"| S["Your app"]
    S -->|"2. Security headers<br/>(browser hardening)"| U
    S -->|"3. Encode output<br/>(no XSS)"| U
    U -->|"4. Antiforgery token<br/>(no CSRF)"| S
    S -->|"5. Parameterized queries<br/>(no injection)"| D[("Database")]
    S -->|"6. Data Protection<br/>(encrypted cookies and tokens)"| U

Security is a stack of small, separate protections; each blocks a different attack.

HTTPS and HSTS

Without TLS everything between the browser and your server (passwords, cookies, tokens) is readable and changeable by anyone on the network path. So production traffic is HTTPS only, and two middlewares help:

  • UseHttpsRedirection() answers a plain-HTTP request with a redirect to the HTTPS address, so a mistyped or old http:// link still ends up secure.
  • UseHsts() adds the Strict-Transport-Security header, which tells the browser "for the next N seconds, never even try plain HTTP for this host". That closes the small window in which the very first plain request could be intercepted. The default lifetime is 30 days; you configure it with AddHsts (MaxAge, IncludeSubDomains, Preload).

HSTS is intentionally cautious: the middleware adds the header only to HTTPS responses, and by default skips loopback hosts (localhost, 127.0.0.1), because a browser that cached HSTS for localhost would break your other local projects. Typical wiring is if (!app.Environment.IsDevelopment()) { app.UseHsts(); }.

Since the sandbox here has no certificate, the next example shows HSTS being (correctly) silent over plain HTTP, next to a middleware that adds the response headers described in the following section.

Security headers

Browsers have strong protections that are opt-in through headers. A small middleware can add them to every response. The most useful ones:

Header What it does
X-Content-Type-Options: nosniff The browser must honor the declared Content-Type instead of guessing, so an uploaded text file cannot be executed as a script
Content-Security-Policy Lists where scripts, styles, images and frames may load from; the strongest defense in depth against XSS, and frame-ancestors controls who may embed your page
X-Frame-Options: DENY Older way to forbid framing (anti-clickjacking); CSP frame-ancestors supersedes it
Referrer-Policy Limits how much of your URL is sent to other sites
Permissions-Policy Switches off browser features you do not use (camera, microphone, geolocation)
Strict-Transport-Security HSTS, as above (HTTPS only)

Also remove information that helps attackers choose exploits: Kestrel's Server: Kestrel header can be turned off with AddServerHeader = false.

C# Security headers and HSTS over plain HTTP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A Content-Security-Policy is the one worth investing time in. default-src 'self' means "only load resources from my own origin", which already blocks injected <script src="https://evil.example/x.js"> and inline scripts. Real sites loosen it deliberately (a CDN, a nonce for a particular inline script) and test with the browser console open, because a too-strict policy simply breaks pages.

Cross-site scripting (XSS)

XSS happens when attacker-supplied text reaches a page as markup or script instead of as text. If a comment contains <script>steal(document.cookie)</script> and you write it into HTML as-is, every visitor runs the attacker's code with your site's privileges.

The cure is output encoding: convert characters that have meaning in the target context into harmless equivalents. The encoding depends on where the text lands:

  • HTML body and attribute values: < becomes &lt;. Razor views, Razor components and Blazor do this automatically for every @expression. The unsafe escape hatches are Html.Raw(...) and MarkupString: treat each use as a security review item.
  • JavaScript strings: use JavaScriptEncoder, or better, put data into a JSON element or data- attribute instead of inlining it in script.
  • URLs: use UrlEncoder for query values.

In minimal APIs, returning a string with Results.Content(text, "text/html") sends it as HTML without encoding, and building HTML with string interpolation is the easiest way to create XSS. Return JSON instead, or encode every dynamic value.

C# Encoding for HTML, JavaScript and URLs, and why parameters beat concatenation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Pay attention to the first two lines. The encoded form is displayed as text by the browser, which is the whole point, and the unsafe attribute line shows how a single quote can break out of an attribute and add an event handler.

SQL injection and other injection

SQL injection is XSS's cousin on the server: user input is concatenated into a query, and the attacker closes the string literal and appends their own SQL. The fix is always the same: never build SQL from strings that contain user input; use parameters. With the SqlCommand-style API (or Dapper, or EF Core with LINQ or FromSql) the SQL text and the values travel separately. This code is read-only here because no database driver is available to the runner:

C#
// Safe: the value is a parameter, never part of the SQL text.
using var command = new SqlCommand("SELECT * FROM Users WHERE Name = @name", connection);
command.Parameters.AddWithValue("@name", userInput);

// EF Core: LINQ is parameterized for you, and FromSql with an interpolated string
// turns each {value} into a parameter (it does NOT concatenate).
var user = await db.Users.Where(u => u.Name == userInput).FirstOrDefaultAsync();
var rows = await db.Users.FromSql($"SELECT * FROM Users WHERE Name = {userInput}").ToListAsync();

// DANGEROUS: FromSqlRaw with string interpolation or concatenation.
var bad = db.Users.FromSqlRaw($"SELECT * FROM Users WHERE Name = '{userInput}'");

The same principle covers every interpreter: operating system commands (Process.Start with a command line built from input), LDAP filters, and XML parsers. Pass arguments as separate values, validate against an allow-list, and never let input choose a file path without checking it (Model Validation covers validating input at the edge).

Cross-site request forgery (CSRF)

Browsers attach cookies to a request automatically, even when the request was triggered by another site. If you are signed in to bank.example and then visit evil.example, a hidden form on the evil page can post to bank.example/transfer, and your cookie goes along. The bank sees an authenticated request and may obey it.

The defenses stack:

  1. SameSite cookies (Lax is now the usual default): the browser withholds the cookie from most cross-site POSTs.
  2. Antiforgery tokens: each form carries a secret token (and a matching cookie) that a foreign site cannot read, so a forged request lacks it. ASP.NET Core issues and checks them with IAntiforgery.
  3. Not using cookies for APIs. A bearer token in an Authorization header is never added automatically by the browser, so token-authenticated APIs are not CSRF-prone.

Since .NET 8, app.UseAntiforgery() plus form binding in minimal APIs does the validation for you: an endpoint that binds form data requires a valid token unless you call DisableAntiforgery(). Razor Pages and MVC forms get hidden token fields from the form tag helper.

C# Antiforgery: forged posts are rejected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Only the first request carries both halves of the proof. In the last case the attacker has a perfectly valid token string but not the matching cookie from the victim's browser, so the check fails. That pairing is the point of the design.

JSON APIs called with fetch from your own single-page app can send the token in a header (RequestVerificationToken), but if the API authenticates with a bearer token rather than a cookie, you do not need antiforgery at all.

The Data Protection API

Whenever ASP.NET Core must hand something private to the client and trust it when it comes back (authentication cookies, antiforgery tokens, TempData, the Identity API's tokens), it uses the Data Protection API. It encrypts and authenticates a payload with keys it manages itself (a "key ring" that rotates, by default every 90 days). You can use it too, for example to create a tamper-proof link for a password reset.

Key ideas:

  • Purpose strings. provider.CreateProtector("Reset.Link.v1") gives a protector tied to that purpose. Data protected for one purpose cannot be unprotected with another, so a token for one feature cannot be replayed in a different one.
  • Time limits. ToTimeLimitedDataProtector() embeds an expiry.
  • Key storage matters in production. The default key ring lives in a folder on the machine, which is fine for one server. With several servers, containers or slot swaps, every instance must share the same keys, or cookies issued by one are unreadable by another. Persist keys to shared storage (a database, blob storage, Redis) with PersistKeysTo..., and protect them at rest.

The example uses an in-memory key ring so it runs anywhere.

C# Protecting data with purposes and an expiry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Open redirects

Login pages often accept ?returnUrl=/orders and redirect there after sign-in. If you redirect to any address, an attacker can send a victim a link such as /login?returnUrl=https://evil.example/fake-login. The victim sees your trusted domain in the link, signs in, and lands on a look-alike site that asks them to "sign in again".

The rule: only redirect to local addresses (starting with a single /). Careful about the sneaky forms: //evil.example and /\evil.example are treated by browsers as external. ASP.NET Core ships the check in Results.LocalRedirect (and Url.IsLocalUrl in MVC), which throws for non-local addresses. The next example validates first so the endpoint can answer politely.

C# Accepting only local return URLs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Everything except a plain path falls back to /home. The same discipline applies to any URL that comes from input and is later used by the server (fetching it, redirecting to it, embedding it): treat it as hostile until it passes an allow-list. Fetching arbitrary URLs from the server is its own attack, called SSRF.

A short security checklist

  • HTTPS everywhere, with UseHttpsRedirection and UseHsts in production.
  • Output encoding by default; audit every Html.Raw, MarkupString and Results.Content(..., "text/html").
  • Parameterized queries only.
  • Antiforgery on every cookie-authenticated form post; SameSite cookies; HttpOnly and Secure flags.
  • Security headers, with a Content-Security-Policy you have tested.
  • Secrets in user secrets or a vault (Environments and Secrets), never in the repository.
  • Shared, persisted Data Protection keys across all instances.
  • Limit abuse with rate limiting (Rate Limiting, Health Checks and Resilience of the App), and keep packages up to date.

Authorization, covered in Authorization: Roles, Policies and Handlers, decides what users may do; this lesson's habits keep the application from being tricked into doing more than it should.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does UseHsts() add no header when you call your app over plain http://localhost?

    A browser must only learn the policy over a secure connection, and the middleware skips localhost, 127.0.0.1 and [::1] so a cached HSTS entry does not break other local sites.
  2. 2. A page shows a user's comment with Results.Content($"<p>{comment}</p>", "text/html"). What is the problem?

    Encoding is automatic in Razor and Blazor expressions, but a hand-built HTML string is sent exactly as written. Encode with HtmlEncoder or use a view.
  3. 3. An attacker has a valid antiforgery token string, but posts from their own browser to your site on behalf of a victim. Why does the request fail?

    Validation compares the request token with the cookie. A forged cross-site request cannot read either of them, and a token without its cookie does not pass.
  4. 4. What is the correct way to avoid SQL injection?

    Filtering characters is fragile. Parameters keep data from ever being parsed as SQL. HTML encoding is for a different context.
  5. 5. Why use a purpose string with CreateProtector?

    The purpose is mixed into key derivation, so a protector for "Invitation" cannot decrypt what the "PasswordReset" protector produced.

Summary

  • Use HTTPS everywhere; UseHsts makes browsers refuse plain HTTP, and it only acts on HTTPS responses.
  • Add security headers (nosniff, a tested CSP, framing and referrer policies) and hide Server.
  • Encode output for the context it lands in; treat Html.Raw and hand-built HTML as dangerous.
  • Cookie-authenticated forms need antiforgery tokens and SameSite cookies; bearer-token APIs are not CSRF-prone.
  • Always use parameterized queries; the same separation of code and data applies to every interpreter.
  • The Data Protection API encrypts and signs payloads with purposes and expiry; share and persist its keys across instances.
  • Redirect only to local URLs.

Next: Background Services and Hosted Services