C# Application Security: Top 10 Vulnerabilities and Protection Methods in .NET
Developing secure applications in C# and the .NET platform is a critically important task for any developer. Even with built-in protection mechanisms, the framework cannot prevent all attacks. In this article, we will analyze the 10 most common vulnerabilities in C# applications, based on the current OWASP Top 10 ranking, and show how to avoid them using code examples.
1. SQL Injection
One of the oldest and most dangerous vulnerabilities. It occurs when user input is directly concatenated into an SQL query.
Vulnerable code:
string query = "SELECT * FROM Users WHERE Username = '" + username + "'";SqlCommand cmd = new SqlCommand(query, connection);Secure code (using parameterized queries):
string query = "SELECT * FROM Users WHERE Username = @username";SqlCommand cmd = new SqlCommand(query, connection);cmd.Parameters.AddWithValue("@username", username);2. Cross-Site Scripting (XSS)
An attack where an attacker injects a malicious script into a web page. In ASP.NET Core, it is important to encode output.
Vulnerable code (Razor):
<div>@Model.UserInput</div>Secure code:
<div>@Html.Encode(Model.UserInput)</div>// Or in ASP.NET Core use @Model.UserInput if you are not using HtmlStringIn ASP.NET Core Razor, output is encoded by default, but when using @Html.Raw() or returning ContentResult with unverified data, the risk returns.
3. Cross-Site Request Forgery (CSRF)
An attack where an attacker forces an authenticated user to perform an unwanted action.
Protection in ASP.NET Core:
// In ConfigureServicesservices.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");
// In the controller[AutoValidateAntiforgeryToken]public class AccountController : Controller{ [HttpPost] [ValidateAntiForgeryToken] public IActionResult ChangePassword(ChangePasswordModel model) { // code }}4. Insecure Deserialization
A dangerous vulnerability, especially when using BinaryFormatter, SoapFormatter, or Newtonsoft.Json with TypeNameHandling.All.
Vulnerable code:
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };var obj = JsonConvert.DeserializeObject(json, settings);Secure code:
// Use System.Text.Json (safe by default)var obj = JsonSerializer.Deserialize<MyType>(json);// Or restrict TypeNameHandling in Newtonsoftvar settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None };5. Authentication and Session Management Flaws
Includes weak passwords, lack of account lockout, unprotected cookies.
Recommendations:
- Use ASP.NET Core Identity with password policies.
- Configure cookie protection:
HttpOnly,Secure,SameSite. - Enable lockout after N failed attempts.
services.ConfigureApplicationCookie(options =>{ options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SameSite = SameSiteMode.Strict; options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.SlidingExpiration = true;});6. Sensitive Data Exposure
Storing passwords in plain text, transmitting data over HTTP, logging secrets.
Secure code:
// Password hashingvar passwordHasher = new PasswordHasher<User>();string hash = passwordHa