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

Code
  
    app.UseHttpsRedirection();
Code
  
    app.UseHsts();

2. Authentication & Authorization

Code
  
    services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});

3. Protect Against XSS (Cross-Site Scripting)

Code
  
    @Html.DisplayFor(model => model.Name)   //  safe
 @Model.Name   //  safe
 @Html.Raw(Model.Name)  //  unsafe unless sanitized

4. Prevent CSRF (Cross-Site Request Forgery)

Code
  
    <form asp-action="PostData">
    @Html.AntiForgeryToken()
</form>
Code
  
    [ValidateAntiForgeryToken]
 public IActionResult PostData(MyModel model) { ... }

5. Secure Cookies

Code
  
    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

Code
  
    builder.Configuration.AddUserSecrets<Program>();

7. Secure Database Access

8. Use Strong Authentication for APIs

9. Logging & Error Handling

Code
  
    if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}

10. Disable Dangerous Features

Code
  
    services.AddCors(options =>
{
    options.AddPolicy("DefaultPolicy", builder =>
        builder.WithOrigins("https://yourapp.com")
               .AllowAnyHeader()
               .AllowAnyMethod());
});

11. Keep Framework & Dependencies Updated

12. Apply Principle of Least Privilege

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.