Security
This file covers the security rules outside the HTTP pipeline: secrets, deserialization, cryptography, and servicing cadence.
- For the rules inside the HTTP pipeline, such as authentication, CSRF, and CORS, and for the Data Protection key ring, see aspnet-core-security.md.
- For HTTPS redirection, the container user, and rate limiting, see aspnet-core.md.
- For supply-chain rules, see ci.md.
- For parameterised SQL, see data-access.md.
Opinions
Secrets
Use the Secret Manager in development and a managed identity to a vault in production. Never put a secret in appsettings*.json. The Secret Manager "doesn't encrypt the stored secrets and shouldn't be treated as a trusted store. It's for development purposes only". Production secrets "should be accessed through a controlled means like Azure Key Vault". (Microsoft Learn: Safe storage of app secrets in development in ASP.NET Core) With a managed identity, the deployment holds no secret at all, because the app needs no stored credential to reach the vault.
// Azure.Extensions.AspNetCore.Configuration.Secrets + Azure.Identity.
// The managed identity works in the deployed app and the second credential is the
// developer's own sign-in, so one code path covers both. Pass the id explicitly:
// the parameterless ManagedIdentityCredential constructor is obsolete as of
// Azure.Identity 1.18.0, and CS0618 is an error under TreatWarningsAsErrors.
builder.Configuration.AddAzureKeyVault(
new Uri($"https://{builder.Configuration["VaultName"]}.vault.azure.net/"),
new ChainedTokenCredential(
new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned),
new AzureCliCredential()));
(Bowden: Using ASP.NET Core with Azure Key Vault; for the explicit system-assigned id, Microsoft Learn: Authenticate Azure-hosted .NET apps to Azure resources using a system-assigned managed identity; and for the obsolete constructor, Azure.Identity: CHANGELOG, 1.18.0-beta.1)
A secret can also leave the process through a log or a diagnostic dump, so review what the app writes. (Meziantou: Prevent accidental disclosure of configuration secrets) Since .NET 10, EF Core redacts inlined constants from the SQL it logs. (.NET Team: Announcing .NET 10) For the logging rules, see logging.md.
Deserialization
Never reference the System.Runtime.Serialization.Formatters compatibility package, and never deserialize untrusted input with a format that names its own types. "Starting in .NET 9, the in-box BinaryFormatter implementation throws exceptions on use, even with the settings that previously enabled its use." (Microsoft Learn: BinaryFormatter disabled across all project types) The compatibility package brings that behaviour back, and the vulnerability with it.
The flaw is type information in the payload, not the binary encoding: "Any deserializer, binary or text, that allows its input to carry information about the objects to be created is a security problem waiting to happen." (Landwerth: BinaryFormatter removed from .NET 9) Keep System.Text.Json on its default contract-based binding. Never let a converter or a polymorphic setting take a type name from the caller. A crafted payload that reaches a type-naming deserializer can run the attacker's code. For an end-to-end demonstration, see Meziantou: Deserialization can be dangerous.
Cryptography: stay on the GA algorithm set
Choose the algorithm from the platform's recommended set, and never implement a primitive yourself. The set below is Microsoft's. (Microsoft Learn: .NET cryptography model) That page was last reviewed in 2021 and doesn't cover AES-GCM or password parameters, so the rules for those two cite their own current sources.
| Purpose | API |
|---|---|
| Symmetric encryption | AesGcm. Aes in CBC mode only for a format that requires it, with an HMAC that you verify before you decrypt |
| Integrity | HMACSHA256 or HMACSHA512 |
| Signatures | ECDsa or RSA |
| Random values | RandomNumberGenerator |
| Password-based key derivation | Rfc2898DeriveBytes.Pbkdf2 |
When a protocol needs X25519 key exchange or AES Key Wrap, use the in-box APIs. .NET 11 adds both, so neither is a reason to take a third-party cryptography package. X25519DiffieHellman.GenerateKey() picks the platform's implementation. Aes.EncryptKeyWrap and Aes.DecryptKeyWrap implement unpadded AES Key Wrap (RFC 3394), "which requires plaintext that's a multiple of 8 bytes". It also needs at least 16 bytes: EncryptKeyWrap throws ArgumentException for an 8-byte key. Where the protocol allows it, Aes.EncryptKeyWrapPadded (RFC 5649) wraps a key of any length. (Microsoft Learn: What's new in .NET libraries for .NET 11)
Encrypt with AesGcm, an authenticated mode, by default. Padded CBC leaks plaintext to an attacker who can tell a padding failure from a successful decryption: "to use padded CBC block ciphers safely, you must combine them with an HMAC (or another data integrity check) that you validate using a constant time comparison before trying to decrypt the data". The alternative is to "change the cipher mode to an authenticated encryption (AE) mode such as GCM or CCM". (Microsoft Learn: Timing vulnerabilities with CBC-mode symmetric decryption using padding)
Use each GCM nonce once. Generate it for each operation from RandomNumberGenerator, and store it beside the ciphertext. Never derive it from a counter you might reset. "There is, over time, a very small chance of generating the same nonce, which can render AES-GCM insecure". (Gordon: Encrypting Properties with System.Text.Json and a TypeInfoResolver Modifier (Part 2)) Rotate a key once it has encrypted enough data to make a 12-byte nonce collision plausible.
static byte[] Encrypt(byte[] key, byte[] plaintext)
{
// A fresh nonce for every call, stored with the ciphertext.
byte[] nonce = RandomNumberGenerator.GetBytes(AesGcm.NonceByteSizes.MaxSize);
byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize];
byte[] ciphertext = new byte[plaintext.Length];
using var aes = new AesGcm(key, tag.Length);
aes.Encrypt(nonce, plaintext, ciphertext, tag);
return [.. nonce, .. tag, .. ciphertext];
}
Let ASP.NET Core Identity hash passwords. Its PasswordHasher runs PBKDF2, and the IterationCount "Default is 100,000". (Microsoft Learn: PasswordHasherOptions.IterationCount) That's ten times the 10,000-iteration floor that Bowden gives below. Under the passkeys-first opinion in aspnet-core-security.md, most new apps never hash a password at all.
To derive a key from a password outside Identity, call Rfc2898DeriveBytes.Pbkdf2 with a salt of at least 8 bytes from RandomNumberGenerator. (Bowden: Creating hashes in .NET) Bowden's 2024 figure of "more than 10000 iterations" is a floor, not a target. No current source states a figure for .NET 10, so justify the count for each application. Argon2id needs a third-party package, because the BCL doesn't ship it.
Post-quantum: IsSupported gates every use
Use MLKem and MLDsa, and check IsSupported at every call site. The algorithms come from the operating system, not the runtime. Linux needs OpenSSL 3.5 or later, and Apple platforms, Android, and the browser have none of them. (Microsoft Learn: Cross-platform cryptography in .NET)
Both classes shipped without [Experimental], but four export and import members keep it under diagnostic SYSLIB5006. So code that moves a key out of the process still opts into an experimental API. Windows support arrived with the same release, and the Learn compatibility table doesn't reflect it yet. SlhDsa and CompositeMLDsa ship with [Experimental] on the classes themselves, so they stay out of the GA set. (Barton: Post-Quantum Cryptography in .NET)
Servicing: take the monthly patch
Rebuild and redeploy after every Patch Tuesday, whether or not your code changed. Security fixes ship on "always the second Tuesday of the month". The platform's instruction is to "Regularly install servicing updates to ensure that your apps are in a secure and supported state". (Microsoft Learn: .NET releases, patches, and support) A container image keeps the runtime it was built with until something rebuilds it. (aspnet-core.md: Hosting and deployment)
CVE-2025-55315 shows what a slow cadence costs. It's a request-smuggling flaw in ASP.NET Core, and Microsoft gave it "a CVSS score of 9.9, their highest ever". An attacker could "Login as a different user", "Make an internal request (SSRF)", or "Bypass CSRF checks". (Lock: Understanding the worst .NET vulnerability ever: request smuggling and CVE-2025-55315) The fix shipped on a Patch Tuesday, and it reaches production only when your pipeline rebuilds and redeploys.
Target a supported framework. .NET 8 and .NET 9 both reached end of support on 2026-11-10, so a project on either gets no more patches. (Damkewala: .NET STS releases supported for 24 months) net11.0, an STS release, and net10.0, an LTS release, are both supported until 2028-11-14. (Microsoft: .NET Support Policy)
Coming next (preview, not yet the opinion)
.NET 11 previews a redesign of unsafe as a compiler-enforced contract between callers and API authors. The plan is "to release the new model and syntax (nominally a C# 16 feature) as a preview in .NET 11 and as a production release in .NET 12". (Lander: Improving C# Memory Safety) For how to turn the preview on, see csharp.md.