Introduction
In this article, we will see the key security rules & best practices for ASP.NET Core projects.
Before we start, please take a look at my last article on ASP.NET Core.
Now, let's get started.
1. Use HTTPS Everywhere
app.UseHttpsRedirection();
app.UseHsts();
2. Authentication & Authorization
Use ASP.NETCore Identity or external providers (OAuth2, OpenID Connect).
Never roll your own auth.
Role-based & policy-based authorization:
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});
3. Protect Against XSS (Cross-Site Scripting)
@Html.DisplayFor(model => model.Name) // safe
@Model.Name // safe
@Html.Raw(Model.Name) // unsafe unless sanitized
4. Prevent CSRF (Cross-Site Request Forgery)
<form asp-action="PostData">
@Html.AntiForgeryToken()
</form>
[ValidateAntiForgeryToken]
public IActionResult PostData(MyModel model) { ... }
5. Secure Cookies
options.Cookie.HttpOnly = true; // JS can’t access
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Only HTTPS
options.Cookie.SameSite = SameSiteMode.Strict; // Prevent CSRF
6. Store Secrets Securely
builder.Configuration.AddUserSecrets<Program>();
7. Secure Database Access
Always use parameterized queries (EF Core does this by default).
Apply least privilege principle to DB accounts.
Validate and sanitize all user input before queries.
8. Use Strong Authentication for APIs
Use JWT or OpenID Connect for APIs.
Short-lived tokens + refresh tokens.
Store tokens securely in HttpOnly cookies or secure storage (not localStorage).
9. Logging & Error Handling
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
Use structured logging with Serilog, Seq, or Application Insights.
Log security events (login attempts, access denials).
10. Disable Dangerous Features
services.AddCors(options =>
{
options.AddPolicy("DefaultPolicy", builder =>
builder.WithOrigins("https://yourapp.com")
.AllowAnyHeader()
.AllowAnyMethod());
});
11. Keep Framework & Dependencies Updated
Always patch to the latest ASP.NET Core version.
Use tools like Dependabot, dotnet list package --outdated.
Remove unused dependencies (minimize attack surface).
12. Apply Principle of Least Privilege
Separate environments (Dev/Test/Prod).
Don’t run the app as admin/root.
Limit file system & DB access to only what’s required.
Note: Following these rules will cover 80–90% of common attack vectors (XSS, CSRF, SQL injection, weak cookies, leaked secrets, etc.).
Conclusion
In this article, I have tried to cover key security rules & best practices for ASP.NET Core projects.