Introduction
In today’s world of cyber threats and data breaches, security is no longer optional—it’s a necessity. As developers, we are responsible for ensuring that our applications are built on secure coding practices.
C# applications, whether built on ASP.NET Core, .NET Framework MVC, Web APIs, or desktop apps, are common targets for attackers. Vulnerabilities such as SQL Injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), broken authentication, insecure file handling, and misconfigured security settings can compromise user data and business reputation.
This article provides a complete application security checklist for C# developers . You can use this as a practical guide to make sure your applications follow the best security practices from design to deployment .
1. Authentication and Authorization
Authentication and authorization are the first line of defense.
Use ASP.NET Identity, OAuth2.0, or OpenID Connect instead of custom authentication logic.
Always hash and salt passwords with PBKDF2, bcrypt, or Argon2.
Enforce multi-factor authentication (MFA) for critical systems.
Implement Role-Based Access Control (RBAC) or Claims-Based Authorization.
[Authorize(Roles = "Admin")]
public IActionResult AdminDashboard()
{
return View();
}
2. Secure Data Access (Prevent SQL Injection)
SQL injection remains one of the most dangerous attacks .
Safe Example (Entity Framework LINQ)
var user = db.Users.FirstOrDefault(u => u.Username == username);
Safe Example (ADO.NET with parameters)
var cmd = new SqlCommand("SELECT * FROM Users WHERE Username = @username", conn);
cmd.Parameters.AddWithValue("@username", username);
Vulnerable Example
var query = $"SELECT * FROM Users WHERE Username = '{username}'";
Checklist : Always use parameterized queries or LINQ . Never concatenate user input.
3. Input Validation and Output Encoding
Unvalidated input can lead to XSS, injection, and logic flaws.
Use Data Annotations or FluentValidation.
Apply whitelisting where possible (e.g., regex for emails and numbers).
Always encode output to prevent XSS.
@Html.DisplayFor(model => model.Comment) // Razor auto-encodes
4. Secure Configuration
Application configuration often exposes sensitive data if not handled properly.
Never hardcode secrets in code. Use Azure Key Vault, AWS Secrets Manager, or environment variables.
Disable detailed error messages in production.
Enforce HTTPS/TLS 1.2+ for all requests.
app.UseHttpsRedirection();
5. Web Security (CSRF, CORS, XSS)
Cross-Site Request Forgery (CSRF)
@Html.AntiForgeryToken()
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SubmitForm(MyModel model)
{
// Safe form submission
}
Cross-Origin Resource Sharing (CORS)
app.UseCors(builder =>
builder.WithOrigins("https://trusteddomain.com")
.AllowAnyHeader()
.AllowAnyMethod());
Cookie Security
6. Logging and Monitoring
Logging is essential for detecting and responding to attacks.
Use structured logging frameworks like Serilog, NLog, or Microsoft.Extensions. Logging.
Never log sensitive data (passwords, tokens, credit card info).
Integrate monitoring with Application Insights, Splunk, or ELK Stack.
_logger.LogInformation("User {UserId} logged in at {Time}", userId, DateTime.UtcNow);
7. API Security
APIs are high-value targets.
Use JWT tokens or OAuth 2.0 for authentication.
Validate token issuer, audience, and expiration .
Implement rate limiting/throttling to prevent brute-force attacks.
Return proper HTTP status codes (401 Unauthorized, 403 Forbidden).
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
});
8. Dependency and Patch Management
Outdated dependencies can expose your app to known vulnerabilities.
Regularly update .NET runtime, NuGet packages, and libraries .
Use tools like OWASP Dependency-Check, GitHub Dependabot, or Snyk.
Remove unused dependencies.
9. File Uploads and Data Protection
File uploads are a common attack vector.
Validate file extensions, size, and MIME type.
Store files outside the web root.
Rename files using GUIDs.
Scan files for malware if required.
var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
var path = Path.Combine("uploads", fileName);
10. Cryptography and Data Protection
Use AES-256 encryption for sensitive data.
Use the Microsoft.AspNetCore.DataProtection API instead of custom crypto.
Use RandomNumberGenerator. Create() for secure random values.
using (var rng = RandomNumberGenerator.Create())
{
byte[] tokenData = new byte[32];
rng.GetBytes(tokenData);
string token = Convert.ToBase64String(tokenData);
}
11. Secure Development Lifecycle (SDLC)
Perform code reviews with a security focus .
Run static code analysis (SonarQube, Roslyn analyzers).
Conduct dynamic testing with OWASP ZAP or Burp Suite.
Apply threat modeling (STRIDE, DREAD) during design.
12. Compliance and Standards
Follow OWASP Top 10 and CWE/SANS Top 25 guidelines.
Ensure compliance with GDPR, PCI-DSS, and HIPAA where required.
Adopt Microsoft Secure Coding Guidelines and NIST standards.
Real-World Security Checklist for C# Developers
Authentication & Authorization
Use ASP.NET Identity / OAuth2 / OpenID Connect
Enforce strong password policies & MFA
Apply role-based or claims-based access control
Data Protection
Parameterize all queries (no string concatenation)
Encrypt sensitive data (AES-256, DPAPI)
Use secure random numbers ( RandomNumberGenerator
)
Web Security
Enable HTTPS/TLS everywhere
Enable CSRF protection in forms
Restrict CORS to trusted domains
Secure cookies ( Secure
, HttpOnly
, SameSite
)
File Handling
Validate file type, size, and MIME type
Store uploads outside web root
Rename files with GUIDs
Logging & Monitoring
Use structured logging (Serilog/NLog)
Never log passwords or tokens
Monitor for suspicious activity
Dependencies & Config
Testing & SDLC
Perform code reviews for security flaws
Run static code analysis (SonarQube, Roslyn analyzers)
Conduct penetration testing (OWASP ZAP, Burp Suite)
Conclusion
Security is not a one-time activity; it’s a continuous process. By following this C# application security checklist , developers can reduce risks from common vulnerabilities, protect sensitive data, and ensure compliance with industry standards.
Golden Rules for Developers:
Validate input, escape output, and parameterize queries.
Use HTTPS and secure cookies.
Protect secrets properly.
Update dependencies regularly.
Log securely and monitor continuously.
By embedding these practices into your development workflow, you’ll create secure, reliable, and resilient C# applications that can withstand today’s evolving cyber threats.