Introduction
Application security has become one of the most critical aspects of modern software development. Whether you are building ASP.NET Core MVC, Web API, or .NET Framework applications, or even desktop apps, securing your application should always be a top priority.
Attackers continuously look for vulnerabilities such as SQL Injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), insecure authentication, and sensitive data exposure.
In this article, we will explore the best practices for application security in C# development with practical recommendations and ready-to-use code snippets.
1. Authentication and Authorization
Use ASP.NET Core Identity, OAuth 2.0, or OpenID Connect for secure authentication.
Always hash and salt passwords using PBKDF2, bcrypt, or Argon2.
Implement multi-factor authentication (MFA) for sensitive apps.
Enforce Role-Based Access Control (RBAC) or Claims-Based Authorization.
[Authorize(Roles = "Admin")]
public IActionResult AdminDashboard()
{
return View();
}
2. Preventing SQL Injection
Always use Entity Framework LINQ or parameterized queries. Never concatenate user input directly into SQL strings.
Safe (Entity Framework LINQ) :
var user = db.Users.FirstOrDefault(u => u.Username == username);
Safe (ADO.NET with parameters) :
var cmd = new SqlCommand("SELECT * FROM Users WHERE Username = @username", conn);
cmd.Parameters.AddWithValue("@username", username);
Vulnerable (SQL Injection) :
var query = $"SELECT * FROM Users WHERE Username = '{username}'";
3. Input Validation and Output Encoding
Validate user input using data annotations or libraries like FluentValidation .
Use whitelisting validation where possible.
Encode all output to prevent XSS attacks.
@Html.DisplayFor(model => model.Comment) // Razor safely encodes output
4. Secure Configuration
Never hardcode secrets (use Azure Key Vault, AWS Secrets Manager, or environment variables ).
Disable detailed error messages in production.
Enforce HTTPS/TLS 1.2+ using middleware.
app.UseHttpsRedirection();
5. Protect Against Cross-Site Attacks
CSRF Protection
@Html.AntiForgeryToken()
And in the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SubmitForm(MyModel model)
{
// Handle form safely
}
CORS Protection
Restrict origins and headers:
app.UseCors(builder =>
builder.WithOrigins("https://trusteddomain.com")
.AllowAnyHeader()
.AllowAnyMethod());
6. Logging and Monitoring
Use structured logging (Serilog, NLog, or Microsoft.Extensions.Logging).
Do not log sensitive data such as passwords or tokens.
_logger.LogInformation("User {UserId} logged in at {Time}", userId, DateTime.UtcNow);
Join the conversation! Your thoughts help the community grow.