Threat Protection

By Syncfusion®, Inc. · Last updated

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.

What you will learn

  • Explain common web threats and the default protections
  • Prevent XSS and render untrusted HTML safely
  • Explain CSRF and how antiforgery tokens stop it
  • Use HTTPS, HSTS and CORS, keep secrets on the server and validate on the server

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

ThreatWhat the attacker doesMain defenceIn this lesson
XSS (cross-site scripting)Puts their own script into your pageEncode outputXSS Protection
CSRF (cross-site request forgery)Makes the user's browser send a request they did not wantAntiforgery tokensCSRF Protection
EavesdroppingReads data travelling over the networkHTTPS and HSTSSecure Communication
Unwanted cross-site callsCalls your API from their own siteCORS policiesSecure Communication
Secret leaksReads keys and passwords from downloaded codeKeep secrets on the serverProtecting Sensitive Data
Tampered requestsSkips your form and sends any dataServer-side validationProtecting Sensitive Data
SQL injectionPuts SQL commands into inputParameters (EF Core does this)Database Handling

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.

Tea Shop pages, forms, API

XSS

CSRF

Eavesdropping

Cross-site calls

Secret leaks

Tampered requests

Six ways in. This lesson shows the defence for each.

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.

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.

Attacker review + script

Server saves the review

Ravi opens reviews

script runs as Ravi

Ravi's data goes to the attacker

One bad review becomes a script in every visitor’s browser.

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.)

  • 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:

WayHowWhen
Encode, then add your own tagsEncode the text, then turn safe markers (like a new line) into your own HTMLSimple formatting
SanitizeAn HTML sanitizer removes every tag and attribute that is not on a safe listRich text from an editor
Use a format, not HTMLLet users write Markdown, and convert it with a library that sanitizesComments, 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.

  • 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:

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.

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.

Ravi's browser has the shop cookie opens a prize page

cheap-prizes.example hidden form

teashop.com POST /transfer cookie is valid...

form post + Ravi's cookie (sent by itself)

The attacker cannot read Ravi’s cookie, but they can make his browser send it.

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).

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.

  • 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.

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.

Browser

Server

HTTP: password=chai123

eavesdropper reads it

Browser

Server

HTTPS: x9#Lq!7pZ...

sees only noise

HTTPS turns readable data into noise for anyone in the middle.

  • 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).

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.

  • 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.

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.

Server sends the app

Anyone's browser

TeaShop.Client.dll ApiKey = sk_live_...

download

.dll file

Whatever is inside a WebAssembly DLL, the user has it too.

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.

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

Where secrets belong instead:

DoDon'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 keyCall 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 vaultCommit .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.

Click Next to see each command.

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.
  • 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.

  • 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

MistakeWrong ideaCorrect ideaWhat goes wrong
@((MarkupString)userText)Blazor makes all HTML safeShow user text with @userText, or sanitize it firstXSS: the attacker's script runs for every visitor
A plain <form method="post"> without <AntiforgeryToken />Forms are protected by themselvesUse <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 wayKeep the check for every form postCSRF attacks succeed
AllowAnyOrigin() on a private APICORS is just a nuisanceList the exact origins with WithOrigins(...)Any site may read your users' data
An API key in WebAssembly code or wwwroot/appsettings.jsonprivate or compiled code hides itKeep secrets on the server; use User Secrets in developmentAnyone can download and use the key
Only validating in the browserThe form is the only way inValidate again on the server; compute prices thereNegative quantities, free orders, bad data

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