Skip to content
Tutorials Center
My learning

Topics

Lesson 159 of 182 ยท Testing and Quality

Secure C# Coding

Write safer C# and ASP.NET Core code - stop SQL injection and XSS, validate paths, hash passwords, block CSRF with antiforgery tokens, keep secrets out of source and use Data Protection.

Most security bugs are not clever. They happen when a program treats text from outside as if it were trusted: a name that becomes part of a SQL command, a file name that escapes its folder, a form post that the user never meant to send. Fixing them is mostly a matter of habits that you can apply while you write ordinary code, and that is what this lesson teaches.

We will go through the problems that cause most real-world incidents in .NET applications: injection, cross-site scripting (XSS), path traversal, weak password storage, cross-site request forgery (CSRF), leaked secrets, and how to encrypt small pieces of data with the Data Protection API. Every example runs here, and each one includes the attack as well as the defense, because you only believe a fix after you have seen what it stops. For the wider picture of who may do what in a web app, see Authentication and Authorization.

Treat everything that crosses a trust boundary as hostile until it is validated: query strings, form fields, headers, cookies, uploaded files, JSON bodies, and even data from your own database that originally came from a user. "Our users are friendly" is not a security control.

The mental model: trust boundaries

Security reviews start by drawing a line around the parts of the system you control and asking where data crosses it. Everything that enters is input and must be validated; everything that leaves toward an interpreter (a database, a browser, a shell, a file system) must be encoded or parameterized for that interpreter.

flowchart LR
    U["Browser or client<br/>(untrusted)"] -->|"1. validate input"| A["Your ASP.NET Core app"]
    A -->|"2. parameterize"| D[("Database")]
    A -->|"3. encode output"| U
    A -->|"4. check path / allow-list"| F["File system"]
    S["Secrets store"] -->|"5. inject at startup"| A

Each arrow that crosses a boundary needs its own defense: validation on the way in, and the right escaping or parameterization on the way out.

Validation tells you whether a value is plausible (an age between 0 and 150). Encoding and parameterization make sure that even a plausible-looking value cannot change the meaning of the command it ends up inside. You need both, and the second one is the one that actually stops injection.

SQL injection

SQL injection happens when user text is glued into a command string. The database cannot tell which part was written by you and which by the attacker.

C# What string concatenation builds

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.

Look at the third line of output: the condition '1'='1' is always true, so the query returns every user. The fourth would end the statement and start a destructive one. An apostrophe in a harmless name like O'Brien already breaks the query, which is a good hint: if your code fails on an apostrophe, it is injectable.

The cure is parameters. The SQL text and the values travel separately, so the value is never parsed as SQL:

C#
// Read-only: needs a database provider package such as Microsoft.Data.SqlClient.
using var command = connection.CreateCommand();
command.CommandText = "SELECT Id, Name FROM Users WHERE Name = @name";
command.Parameters.AddWithValue("@name", userName);   // data, never code
using var reader = command.ExecuteReader();

With Entity Framework Core, LINQ queries are parameterized for you. The risk returns when you call raw SQL. Use the interpolated overloads, which turn each into a parameter, and avoid building the string yourself:

C#
// Read-only: needs the Microsoft.EntityFrameworkCore package.
var safe = db.Users.FromSql($"SELECT * FROM Users WHERE Name = {userName}");        // parameterized
var unsafe1 = db.Users.FromSqlRaw("SELECT * FROM Users WHERE Name = '" + userName + "'"); // injectable!

Parameters protect values only. You cannot parameterize a table name, a column name or ORDER BY direction, so for those, map the user's choice to a fixed set with an allow-list (a switch expression returning a hard-coded identifier). The database chapter Entity Framework Core shows the safe query styles in more detail, and SQL and NoSQL from C# covers the ADO.NET side.

The same idea applies to every interpreter: LDAP filters, OS commands (Process.Start with an argument list instead of one shell string, see Environment and Process), XML (disable DTD processing), and regular expressions built from user text (use Regex.Escape, and pass a match timeout).

Cross-site scripting and output encoding

XSS is injection into the browser. If you echo user text into a page unencoded, an input such as <script>...</script> runs in the visitor's browser with your site's privileges. Razor encodes everything by default, so @Model.Comment is safe. The danger is in the escape hatches: @Html.Raw(...), MarkupString in Blazor, string-concatenated HTML in a minimal API, and innerHTML in your JavaScript.

When you must produce HTML or URLs yourself, use the encoders from the base library:

C# Encoding for HTML, URLs and attributes

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.

The encoded text is displayed as text by the browser instead of being run. Remember that the correct encoding depends on the context: HTML body, HTML attribute, JavaScript string, URL and CSS each have different rules, which is another reason to prefer a templating engine that knows the context over hand-built strings. A Content-Security-Policy response header adds a second line of defense by telling browsers which scripts may run at all.

Path traversal

If a user supplies a file name, ../../ can walk out of the folder you meant to expose. Never pass user input straight to Path.Combine and open the result. Resolve the full path and check that it is still inside the allowed root:

C# Keeping file access inside a root folder

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.

Two details matter. Path.Combine quietly discards the first part when the second is an absolute path (/etc/passwd), which is why the check happens after GetFullPath. And the prefix includes a trailing separator so that /srv/uploads-evil does not pass a naive StartsWith("/srv/uploads"). Better still, do not use the user's name at all: store uploads under a generated identifier such as a GUID and keep the original name as metadata. More on paths in Files and Paths.

Storing passwords

Never store passwords, and never store them with a fast hash like plain SHA-256. If your database leaks, fast hashes can be guessed at billions per second. Use a deliberately slow, salted password hash. In ASP.NET Core Identity this is already done for you (PasswordHasher<TUser>, PBKDF2 with a high iteration count). Writing it by hand is only for understanding, and the building blocks are in the base library:

C# Salted PBKDF2 hashing with constant-time compare

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.

The salt is random per user, so two users with the same password get different stored values and precomputed "rainbow tables" are useless. The iteration count makes each guess expensive, and storing it inside the string lets you raise it later and re-hash on the next successful login. FixedTimeEquals compares without stopping at the first difference, so the time taken does not reveal how many leading bytes matched. Use RandomNumberGenerator for anything security related; System.Random is predictable.

Cross-site request forgery (CSRF)

Browsers attach cookies automatically. If you are logged in to a bank and visit an evil page, that page can make your browser submit a form to the bank, and the request arrives with your session cookie. The server cannot tell it from a real submit. CSRF protection adds something the attacker's page cannot know: an antiforgery token that the real page received earlier and must send back with the request.

sequenceDiagram
    participant B as Browser
    participant S as Server
    B->>S: GET /form
    S-->>B: HTML with token + antiforgery cookie
    B->>S: POST /transfer (cookie + token)
    S->>S: do token and cookie match?
    S-->>B: 200 OK
    Note over B,S: A forged POST from another site<br/>has the cookie but no valid token: 400

The antiforgery cookie is sent automatically, but the token must be copied into the request by code from your own page, which other sites cannot do.

ASP.NET Core includes this in the shared framework. Razor Pages and MVC forms add the token for you; for minimal APIs you register the middleware and require the token:

C# Antiforgery tokens in a minimal API

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.

Two practical notes. First, CSRF is a problem of cookie-based authentication; an API that reads an Authorization: Bearer header from JavaScript is not exposed to it, because the browser never adds that header on its own. Second, SameSite=Lax (the default for modern cookies) already blocks many cross-site posts, but it is a layer, not a replacement: keep antiforgery on every state-changing request (POST, PUT, PATCH, DELETE) and never change state in a GET.

Secrets management

A secret is anything that grants access: connection strings with passwords, API keys, signing keys, certificates. The rules are short:

  1. Never commit secrets to source control. Removing them in a later commit does not help, because the history keeps them. If one leaked, rotate it.
  2. Keep them out of the build output and out of logs, error pages and exception messages.
  3. Load them from the environment at run time, so the same build runs in every environment with different secrets.
  4. Give each environment its own secrets, and give each secret the least privilege it needs.

In development, the Secret Manager stores values in your user profile instead of the project folder. In production you use environment variables, or better, a vault such as Azure Key Vault, AWS Secrets Manager or HashiCorp Vault, ideally with a managed identity so there is no password to store at all.

Terminal
# Read-only: commands for your own machine.
dotnet user-secrets init
dotnet user-secrets set "Payments:ApiKey" "sk_test_example"

The configuration system layers these sources, and later sources override earlier ones. Your code reads one setting name and does not care where the value came from:

C# Layered configuration: file, then environment

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.

Real projects bind sections to typed options, as described in Configuration and Options. Fail at startup if a required secret is missing, so you find out on deploy instead of at the first payment. And never log a secret: log that it exists, or a masked form like the one above.

Data Protection: encrypting small values

Sometimes you need to hand a value to the user and trust it when it comes back: a password-reset link, an "unsubscribe" token, a cookie payload. ASP.NET Core ships the Data Protection API for this. You ask for a protector with a purpose string; it encrypts and signs data so only a protector with the same purpose can read it.

C# Protecting and unprotecting data

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.

The purpose string isolates uses from each other: a token made for password reset cannot be replayed as a login cookie. Tampering is detected because the data is authenticated, not just encrypted. In a real app you call builder.Services.AddDataProtection(), persist the key ring to storage all your servers share (a database, a blob, a Redis key) and consider protecting the keys at rest; with the default per-machine keys, a second server or a restart in a container would not be able to read old tokens. For tokens that should expire, the ToTimeLimitedDataProtector() extension adds a lifetime.

Data Protection is for short-lived values that your app both creates and reads. It is not a replacement for database encryption or for hashing passwords, and it is not meant for long-term archives, because keys rotate.

A short security checklist

  • Parameterize every query; allow-list identifiers you cannot parameterize.
  • Let Razor encode output; encode by hand for the right context if you build HTML yourself.
  • Resolve and check every user-supplied path; prefer generated file names.
  • Use Identity or PBKDF2/Argon2 with salts; never invent your own crypto.
  • Require antiforgery tokens for cookie-authenticated state changes.
  • Keep secrets out of source and logs; rotate any that leaked.
  • Use HTTPS everywhere (UseHttpsRedirection, UseHsts), keep packages updated, and enable the .NET analyzers described in Analyzers and Style.
  • Write tests for the abuse cases (injection strings, ../, missing tokens) so a refactor cannot quietly remove a defense. Testing Fundamentals shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What actually prevents SQL injection?

    Parameters keep the SQL text and the values separate. Filtering characters is fragile and easy to bypass, whereas a parameter cannot change the structure of the command.
  2. 2. Why does the path check use Path.GetFullPath before comparing with the root folder?

    A name like ../../secret only reveals where it points after it is combined and normalized. Checking the raw text would miss the escape.
  3. 3. Which is the right way to store a user's password?

    Salting defeats precomputed tables, and a slow hash makes bulk guessing expensive. Identity's PasswordHasher does this for you.
  4. 4. A site authenticates users with cookies. Why is it exposed to CSRF?

    The cookie rides along automatically, so the server cannot tell a forged request from a real one without an additional token that only the real page knows.
  5. 5. What does the purpose string passed to CreateProtector do?

    Different purposes derive different keys, which stops a token made for one feature from being replayed in another.

Summary

  • Treat all external input as untrusted; validate it on the way in and encode or parameterize it on the way out.
  • Use command parameters (and EF Core's interpolated FromSql) to stop SQL injection; allow-list identifiers.
  • Razor encodes output by default; avoid Html.Raw, and use WebUtility.HtmlEncode when building HTML yourself.
  • Resolve user-supplied paths with Path.GetFullPath and check them against a root with a trailing separator.
  • Hash passwords with a salted, slow algorithm (Identity, or PBKDF2 via Rfc2898DeriveBytes.Pbkdf2) and compare with FixedTimeEquals.
  • Cookie-authenticated state changes need antiforgery tokens; never change state in a GET.
  • Keep secrets in user secrets, environment variables or a vault, never in source control or logs.
  • Data Protection encrypts and signs short-lived values per purpose; persist its key ring in production.

Next: Integration Testing ASP.NET Core