.NET gives you a lot of security by default — parameterised queries in EF Core, automatic escaping in Razor, sensible cookie settings in ASP.NET Core. Most real vulnerabilities come from stepping outside those defaults. This guide covers the places where that happens and what to do instead.
1. SQL injection#
EF Core parameterises LINQ queries, so ordinary use is safe. Two places are not:
// Dangerous
var sql = $"SELECT * FROM Products WHERE Name = '{name}'";
var products = context.Products.FromSqlRaw(sql).ToList();
// Safe - each embedded value becomes a parameter
var products = context.Products
.FromSqlInterpolated($"SELECT * FROM Products WHERE Name = {name}")
.ToList();
// Or explicitly
var products = context.Products
.FromSqlRaw("SELECT * FROM Products WHERE Name = {0}", name)
.ToList();
FromSqlInterpolated looks like ordinary string interpolation and is not — that is the whole point of it. Building the string yourself and passing it to FromSqlRaw is exactly the hole it exists to close.
With Dapper or ADO.NET, always pass parameters:
await connection.QueryAsync<Product>(
"SELECT * FROM Products WHERE Name = @name", new { name });
private static readonly HashSet<string> Sortable =
new(StringComparer.OrdinalIgnoreCase) { "Name", "Price", "CreatedAt" };
if (!Sortable.Contains(sortColumn)) sortColumn = "Name";
2. Cross-site scripting#
Razor escapes everything by default:
<p>@Model.Comment</p> <!-- escaped, safe -->
<p>@Html.Raw(Model.Comment)</p> <!-- NOT escaped -->
Html.Raw is the one thing that turns the protection off. Search for it in any codebase you inherit; every occurrence needs justifying.
Passing data into JavaScript needs JSON encoding, not HTML encoding:
<script>
const user = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.Name));
</script>
Better still, put it in a data attribute and read it from script, which avoids the question entirely.
3. Secrets#
dotnet user-secrets init
dotnet user-secrets set "ConnectionStrings:Default" "Server=...;Password=..."
User secrets are stored outside the project folder, so they cannot be committed by accident. In production, use environment variables or a managed vault:
builder.Configuration.AddAzureKeyVault(vaultUri, new DefaultAzureCredential());
export ConnectionStrings__Default="Server=db;Database=shop;"
The double underscore expresses nesting in an environment variable name.
4. Passwords#
// Never
var hash = Convert.ToHexString(MD5.HashData(bytes));
var hash = Convert.ToHexString(SHA256.HashData(bytes));
Both are fast, which is exactly wrong for passwords. ASP.NET Core Identity handles this correctly, and its hasher can be used on its own:
var hasher = new PasswordHasher<User>();
string hash = hasher.HashPassword(user, password);
var result = hasher.VerifyHashedPassword(user, hash, attempt);
if (result == PasswordVerificationResult.SuccessRehashNeeded)
{
// store an updated hash with current parameters
}
Or use a dedicated library for Argon2 or bcrypt. Whichever you choose, size the database column generously — a truncated hash fails verification for every user.
5. Randomness#
// Predictable - fine for shuffling, unsafe for anything granting access
var random = new Random();
// Cryptographically secure
string token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
int code = RandomNumberGenerator.GetInt32(100_000, 1_000_000);
Session identifiers, password reset tokens, API keys and one-time codes must all come from RandomNumberGenerator.
Compare secrets in constant time so an attacker cannot learn from how long the comparison takes:
bool ok = CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(provided),
Encoding.UTF8.GetBytes(expected));
6. Authentication and authorisation#
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.FromSeconds(30),
};
});
All four validation flags matter. Turning off issuer or audience validation to make something work in development is a common shortcut that removes most of the token’s meaning.
[Authorize]
public class OrdersController : ControllerBase
{
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var order = await _repo.GetAsync(id);
if (order is null) return NotFound();
// Authorisation, not just authentication
if (order.UserId != User.GetUserId()) return Forbid();
return Ok(order);
}
}
7. Cookies and CSRF#
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
options.ExpireTimeSpan = TimeSpan.FromHours(8);
options.SlidingExpiration = true;
});
Razor Pages and MVC add antiforgery tokens to forms automatically. For an API called with fetch, send the token in a header and validate it:
[ValidateAntiForgeryToken]
public async Task<IActionResult> Update(OrderModel model) { }
8. Deserialization#
// Dangerous - can construct arbitrary types
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All // do not do this
};
Type name handling in Newtonsoft.Json lets the incoming JSON choose which class to instantiate, which has been the root of real remote code execution vulnerabilities. System.Text.Json does not offer it by default, which is one reason to prefer it.
BinaryFormatter is removed in modern .NET for the same reason. If you find it in old code, replacing it is a security fix rather than a tidy-up.
9. File uploads and paths#
var allowed = new Dictionary<string, string>
{
["image/jpeg"] = ".jpg",
["image/png"] = ".png",
};
if (!allowed.TryGetValue(file.ContentType, out var extension))
return BadRequest("Only JPEG and PNG images are accepted");
if (file.Length > 5 * 1024 * 1024)
return BadRequest("File too large");
// Generate the name - never trust the one supplied
var name = Guid.NewGuid().ToString("N") + extension;
var path = Path.Combine(_uploadRoot, name);
await using var stream = System.IO.File.Create(path);
await file.CopyToAsync(stream);
// Reading a file by name
var root = Path.GetFullPath(_uploadRoot);
var target = Path.GetFullPath(Path.Combine(root, Path.GetFileName(name)));
if (!target.StartsWith(root + Path.DirectorySeparatorChar))
return NotFound();
Generating your own filename removes several problems at once: traversal, collisions, and executable content smuggled in under an image extension.
10. Dependencies and headers#
dotnet list package --vulnerable --include-transitive
dotnet list package --outdated
Run the first in your build pipeline so a new advisory fails the build rather than waiting to be noticed.
app.Use(async (context, next) =>
{
var headers = context.Response.Headers;
headers["X-Content-Type-Options"] = "nosniff";
headers["Referrer-Policy"] = "same-origin";
headers["Content-Security-Policy"] = "default-src 'self'";
await next();
});
app.UseHsts();
app.UseHttpsRedirection();
A checklist#
- No
FromSqlRawwith interpolated strings - No
Html.Rawon user content - Secrets in user-secrets, environment variables or a vault
- Passwords hashed with Identity or Argon2
- Tokens from
RandomNumberGenerator - Ownership checked on every record fetched by identifier
- Cookies HttpOnly, Secure and SameSite
- No
TypeNameHandling, noBinaryFormatter - A vulnerability scan in the build
- Detailed errors off in production
Questions people ask#
Is ASP.NET Core secure by default?
Largely, for the things it handles — escaping, antiforgery, cookie flags, parameterised queries. It cannot protect you from missing authorisation checks or secrets in source control.
Should I write my own authentication?
No. Use ASP.NET Core Identity or an external provider. Password reset, lockout, token expiry and rotation all have details that are easy to get subtly wrong.
System.Text.Json or Newtonsoft?
System.Text.Json for new code — faster, and without the type-handling feature that caused deserialization vulnerabilities. Newtonsoft remains more flexible for unusual mappings.
How do I test for these?
Static analysis catches some, dependency scanning catches known library issues, and a penetration test catches logic flaws such as missing ownership checks. The first two belong in your build.
Where to go next#
- C# and databases — parameterised queries in context.
- C# and ASP.NET Core — where most of this applies.
- C# deployment — production configuration.