It does not matter how clean your architecture is or how fast your queries run - if an attacker can read another user's orders or forge a token, none of that matters.
Most API security problems come from skipping the basics:
- Not updated NuGet package with security vulnerability
- Missing validation check
- Weak authentication setup
- An over-permissive CORS policy
- A secret committed to source control.
The good news is that ASP .NET Core gives you almost everything you need built in.
Over the years, I have shipped and reviewed many .NET APIs, and the same set of practices keeps them safe.
Here are 18 of them, each with the code to apply it.
In this post, we will explore:
- Enforce HTTPS everywhere
- Authenticate with tokens, not sessions
- Validate the JWT signature, issuer, audience, and lifetime
- Authorize with policies, not just [Authorize]
- Apply the principle of least privilege
- Validate and sanitize all input
- Protect against over-posting / mass assignment
- Validate content types and limit request size
- Use parameterized queries and EF Core
- Implement rate limiting and throttling
- Configure CORS restrictively
- Return minimal error detail
- Set security headers
- Store secrets securely
- Enforce CSRF protection where relevant
- Version your API and deprecate insecure endpoints
- Log and audit security events
- Keep dependencies patched
Let's dive in.
1. Enforce HTTPS Everywhere
Every request to your API should travel over an encrypted connection.
Without HTTPS, tokens, passwords, and personal data move in plain text, where anyone on the network path can read them.
Plain HTTP also opens the door to downgrade attacks, in which an attacker forces a client to use an insecure connection.
ASP .NET Core gives you two tools. UseHttpsRedirection redirects HTTP requests to HTTPS, and HSTS (HTTP Strict Transport Security) tells browsers to only ever connect over HTTPS:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHsts(options =>
{
options.MaxAge = TimeSpan.FromDays(365);
options.IncludeSubDomains = true;
options.Preload = true;
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
app.UseHttpsRedirection();
UseHttpsRedirection upgrades any HTTP request to HTTPS.
UseHsts adds the Strict-Transport-Security header, so compliant browsers refuse to talk to your API over plain HTTP at all - which blocks downgrade attacks.
HSTS is skipped during development because you often use http://localhost.
For the full setup, see Configuring HTTPS Redirection and HSTS in ASP .NET Core.
👉 Read the full article on my newsletter: https://antondevtips.com/blog/rest-api-security-best-practices-in-aspnetcore
Top comments (0)