Application security

suggest change

Building secure .NET applications requires applying defense-in-depth principles across data storage, network transport, user input handling, and object serialization. Modern C# and ASP.NET Core provide built-in security abstractions to safeguard against the OWASP Top 10 vulnerabilities.

Preventing SQL Injection

Never construct SQL queries by concatenating raw user strings. Use parameterized queries with ADO.NET, Dapper, or Entity Framework Core:

using System.Data;
using Microsoft.Data.SqlClient;

public class UserRepository
{
    private readonly string _connectionString;

    public UserRepository(string connectionString) => _connectionString = connectionString;

    public async Task<User?> GetUserByEmailAsync(string email)
    {
        const string sql = "SELECT Id, Username, Email FROM Users WHERE Email = @Email";

        await using var connection = new SqlConnection(_connectionString);
        await using var command = new SqlCommand(sql, connection);

        // Parameterized value ensures SQL query structure cannot be altered:
        command.Parameters.Add("@Email", SqlDbType.NVarChar, 255).Value = email;

        await connection.OpenAsync();
        await using var reader = await command.ExecuteReaderAsync();

        if (await reader.ReadAsync())
        {
            return new User(
                reader.GetInt32(0),
                reader.GetString(1),
                reader.GetString(2)
            );
        }

        return null;
    }
}

In Entity Framework Core, LINQ queries like context.Users.Where(u => u.Email == email) are parameterized automatically by the query provider.

Protecting Sensitive Data with Data Protection API

ASP.NET Core includes the Data Protection API (Microsoft.AspNetCore.DataProtection) to encrypt and sign sensitive strings (such as tokens, session identifiers, and sensitive query parameters):

using Microsoft.AspNetCore.DataProtection;

public class TokenService
{
    private readonly IDataProtector _protector;

    // Use a unique purpose string to isolate keys and ciphertext
    public TokenService(IDataProtectionProvider provider)
    {
        _protector = provider.CreateProtector("App.UserVerification.v1");
    }

    public string ProtectPayload(string sensitiveData)
    {
        // Encrypts and cryptographically signs the data
        return _protector.Protect(sensitiveData);
    }

    public string UnprotectPayload(string protectedData)
    {
        // Validates signature and decrypts
        return _protector.Unprotect(protectedData);
    }
}

Cross-Site Request Forgery (CSRF / XSRF) Mitigation

State-changing HTTP requests (POST, PUT, DELETE) must validate anti-forgery tokens:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
[AutoValidateAntiforgeryToken] // Automatically validates anti-forgery tokens on non-GET/HEAD requests
public class ProfileController : ControllerBase
{
    [HttpPost("update-email")]
    public IActionResult UpdateEmail([FromBody] UpdateEmailModel model)
    {
        // Token validated before reaching action body
        return Ok();
    }
}

The antiforgery filters are registered by AddControllersWithViews() / AddMvc() (or AddRazorPages()). With plain AddControllers(), [AutoValidateAntiforgeryToken] fails at runtime with InvalidOperationException: No service for type '...AutoValidateAntiforgeryTokenAuthorizationFilter' has been registered.

In Razor Pages and MVC views, forms created with <form method="post"> automatically include hidden anti-forgery token input elements.

Secret and Configuration Management

Never commit passwords, API keys, or connection strings into version control:

Access secrets via standard configuration binding:

string apiKey = configuration["Authentication:ApiKey"]
    ?? throw new InvalidOperationException("API Key not configured");

Safe Serialization

Historical .NET applications suffered from remote code execution vulnerabilities due to BinaryFormatter. Modern .NET has permanently deprecated BinaryFormatter:

using System.Text.Json;

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    MaxDepth = 32 // Prevent denial-of-service from deeply nested JSON payloads
};

User user = JsonSerializer.Deserialize<User>(jsonPayload, options)!;

Enforcing HTTPS and Secure Headers

In Program.cs, ensure transport encryption and security headers are enforced:

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    // HTTP Strict Transport Security (HSTS)
    app.UseHsts();
}

app.UseHttpsRedirection();

// Security headers middleware
app.Use(async (context, next) =>
{
    context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
    context.Response.Headers.Append("X-Frame-Options", "DENY");
    context.Response.Headers.Append("Content-Security-Policy", "default-src 'self'");
    await next();
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents