ASP.NET Core  

Key Security Rules & Best Practices for ASP.NET Core Projects

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

  • Enforce HTTPS

  
    app.UseHttpsRedirection();
  
  • Add HSTS (HTTP Strict Transport Security)

  
    app.UseHsts();
  
  • Redirect all HTTP to HTTPS in reverse proxies (NGINX, IIS, Azure).

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"));
});
  
  • Secure API endpoints with [Authorize]

3. Protect Against XSS (Cross-Site Scripting)

  • Razor automatically HTML-encodes output:

  
    @Html.DisplayFor(model => model.Name)   //  safe
 @Model.Name   //  safe
 @Html.Raw(Model.Name)  //  unsafe unless sanitized
  
  • Use libraries like Ganss.XSS to sanitize user input.

  • Set Content Security Policy (CSP) headers.

4. Prevent CSRF (Cross-Site Request Forgery)

  • MVC & Razor Pages have anti-forgery tokens built-in:

  
    <form asp-action="PostData">
    @Html.AntiForgeryToken()
</form>
  
  • In controllers:

  
    [ValidateAntiForgeryToken]
 public IActionResult PostData(MyModel model) { ... }
  
  • For APIs: use JWT or the Double Submit Cookie pattern instead.

5. Secure Cookies

  • Use cookie options :

  
    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

  • Never hardcode secrets (DB passwords, API keys) in appsettings.json .

  • Use:

    • User Secrets (for development).

    • Azure Key Vault / AWS Secrets Manager / HashiCorp Vault (for production).

  
    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

  • Don’t expose stack traces to users:

  
    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

  • Turn off directory browsing.

  • Don’t expose detailed errors in production.

  • Limit CORS :

  
    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.