Secure Coding in .NET

1. Introduction

Secure coding is the foundation of building resilient .NET applications. This guide covers the most critical practices you should adopt today to protect your software from common vulnerabilities.

2. Threat Modeling

Before writing code, identify potential threats using methodologies like STRIDE.

// Example: Simple threat model outline
class ThreatModel
{
    public string Asset { get; set; }
    public string Threat { get; set; }
    public string Mitigation { get; set; }
}

3. Input Validation

Never trust user input. Use built‑in validation attributes and regular expressions.

using System.ComponentModel.DataAnnotations;

public class RegisterModel
{
    [Required]
    [StringLength(50, MinimumLength = 3)]
    public string Username { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [RegularExpression(@"^\d{4,6}$", ErrorMessage = "PIN must be 4‑6 digits")]
    public string Pin { get; set; }
}

4. Authentication & Authorization

Leverage ASP.NET Core Identity and policies.

// Startup.cs
services.AddAuthentication()
        .AddCookie();

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

5. Cryptography

Use the System.Security.Cryptography namespace and avoid custom algorithms.

using System.Security.Cryptography;

public static string HashPassword(string password)
{
    using var sha256 = SHA256.Create();
    var bytes = System.Text.Encoding.UTF8.GetBytes(password);
    var hash = sha256.ComputeHash(bytes);
    return Convert.ToBase64String(hash);
}

6. Secure Configuration

Store secrets in Azure Key Vault or user‑secrets; never hard‑code them.

// appsettings.json (do NOT store secrets here)
{
  "ConnectionStrings": {
    "Default": "Server=.;Database=AppDb;Trusted_Connection=True;"
  }
}

7. Testing & Review

Integrate static analysis (Roslyn analyzers) and dynamic scanning (OWASP ZAP).

// .csproj snippet for Roslyn analyzers

  

8. Conclusion

Adopting these practices will dramatically reduce the risk surface of your .NET applications. Keep learning, stay updated on security advisories, and incorporate security into every phase of development.

Comments