Overview +

Secure coding best practices help developers protect applications from common vulnerabilities. The guidance below aligns with the OWASP Top Ten and Microsoft’s security development lifecycle (SDL).

  • Adopt a secure development lifecycle.
  • Validate all inputs.
  • Use strong authentication and authorization.
  • Apply proper cryptographic controls.
  • Handle errors securely.

Input Validation +

Principles

  • Validate on both client and server sides.
  • Prefer whitelisting over blacklisting.
  • Use built‑in framework validators when available.

Common Patterns

using System.Text.RegularExpressions;

public bool IsValidEmail(string input) {
    var pattern = @"^[^\s@]+@[^\s@]+\.[^\s@]+$";
    return Regex.IsMatch(input, pattern);
}

Resources

See Input Validation Guide for deeper coverage.

Authentication & Authorization +

  • Use Windows Authentication or Azure AD when possible.
  • Never store plain‑text passwords – always hash with PBKDF2, bcrypt, or Argon2.
  • Apply least‑privilege principles to all resources.
// Example: Password hashing with PBKDF2
using System.Security.Cryptography;

public static string HashPassword(string password, out byte[] salt) {
    using var rng = RandomNumberGenerator.Create();
    salt = new byte[16];
    rng.GetBytes(salt);
    var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100_000, HashAlgorithmName.SHA256);
    return Convert.ToBase64String(pbkdf2.GetBytes(32));
}

Cryptography +

Prefer high‑level APIs over raw cryptographic primitives. Use the System.Security.Cryptography namespace.

Data Protection API (DPAPI)

using System.Security.Cryptography;
using System.Text;

public static byte[] ProtectData(string plainText) {
    byte[] data = Encoding.UTF8.GetBytes(plainText);
    return ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser);
}

Transport Security

Enforce TLS 1.2+ for all network communications. Disable older protocols via ServicePointManager.SecurityProtocol.

Error Handling & Logging +

  • Never reveal stack traces or internal details to end users.
  • Log errors securely using ILogger with appropriate sensitivity classification.
  • Sanitize any data that may be written to logs.
try {
    // Sensitive operation
}
catch (Exception ex) {
    _logger.LogError(ex, "Unexpected error while processing request.");
    // Return generic error message
    return StatusCode(500, "An internal error occurred.");
}

Secure Coding Tools +

  • Visual Studio Analyzer – enable security ruleset.
  • Microsoft Threat Modeling Tool.
  • Static analysis: SonarQube, Coverity.
  • Dynamic testing: OWASP ZAP, Burp Suite.

References +