ASP.NET  

Data Security in ASP.NET Core MVC Applications

Introduction

Data security is one of the most critical concerns when building ASP.NET Core MVC applications. From user credentials to financial transactions, sensitive data must be protected against threats such as SQL Injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and unauthorized access.

In this article, we’ll explore end-to-end data security practices in ASP.NET Core MVC applications with real-world code examples and best practices that you can apply directly in your projects.

1. Enforce HTTPS Everywhere

Always use TLS/SSL to ensure secure communication between the client and server.

Program.cs

  
    builder.Services.AddHttpsRedirection(options =>
{
    options.HttpsPort = 443;
});

var app = builder.Build();
app.UseHttpsRedirection();
  

Never transmit sensitive data over plain HTTP.

2. Secure Authentication and Authorization

ASP.NET Core provides Identity for authentication, or you can use external providers like Google, Azure AD, or JWT tokens.

Authorization Policy Example

  
    builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});
  

Controller Usage

  
    [Authorize(Policy = "AdminOnly")]
public IActionResult AdminDashboard()
{
    return View();
}
  

Always store passwords using hashing algorithms. ASP.NET Core Identity uses PBKDF2 by default.

3. Protect Sensitive Configuration Data

Never hardcode credentials or API keys in your appsettings.json .

Development → Use User Secrets

  
    dotnet user-secrets set "DbPassword" "SuperSecurePassword123!"
  

Production → Use Azure Key Vault

  
    builder.Configuration.AddAzureKeyVault(
    new Uri("https://myvault.vault.azure.net/"),
    new DefaultAzureCredential());
  

This keeps sensitive data out of source control.

4. Encrypt Sensitive Data at Rest

If your app handles PII (Personally Identifiable Information) such as SSN, credit card numbers, or health records, use encryption.

AES Encryption Helper

  
    public static class EncryptionHelper
{
    private static readonly string Key = "YourEncryptionKey1234"; // Store securely

    public static string Encrypt(string plainText)
    {
        using var aes = Aes.Create();
        var encryptor = aes.CreateEncryptor(Encoding.UTF8.GetBytes(Key), aes.IV);
        using var ms = new MemoryStream();
        ms.Write(aes.IV, 0, aes.IV.Length);
        using var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
        using (var sw = new StreamWriter(cs)) sw.Write(plainText);
        return Convert.ToBase64String(ms.ToArray());
    }
}
  

Store only encrypted values in your database.

5. Validate Input & Prevent SQL Injection

ASP.NET Core Entity Framework Core automatically parameterizes queries, protecting against SQL injection.

Wrong (Vulnerable)

  
    var user = _context.Users.FromSqlRaw(
    $"SELECT * FROM Users WHERE Username = '{username}'").FirstOrDefault();
  

Correct (Safe)

  
    var user = await _context.Users
    .FirstOrDefaultAsync(u => u.Username == username);
  

Always use LINQ queries or parameterized SQL.

6. Prevent Cross-Site Scripting (XSS)

ASP.NET Core Razor automatically encodes output.

  
    <p>@Model.Name</p> <!-- Safe -->
  

If you must allow HTML.

  
    @Html.Raw(Model.Description) // Use carefully
  

Use libraries like Ganss.XSS to sanitize user-generated content.

7. Enable CSRF Protection

ASP.NET Core MVC provides built-in CSRF protection with anti-forgery tokens.

Controller

  
    [HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SaveData(MyModel model)
{
    // Save logic
    return RedirectToAction("Index");
}
  

View

  
    <form asp-action="SaveData" method="post">
    @Html.AntiForgeryToken()
    <button type="submit">Submit</button>
</form>
  

This prevents malicious sites from posting forms on behalf of logged-in users.

8. Secure Cookies & Sessions

Always configure cookies with HttpOnly and Secure flags.

  
    builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.SlidingExpiration = true;
});
  

This prevents cookie theft via JavaScript.

9. Secure File Uploads

If your app allows file uploads.

  • Validate file types & sizes.

  • Store files outside. wwwroot

  • Rename files to avoid execution.

Example validation

  
    if (!file.ContentType.StartsWith("image/"))
    throw new Exception("Invalid file type!");
  

10. Enable Security Headers

Add middleware to strengthen browser protections.

  
    app.Use(async (context, next) =>
{
    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
    context.Response.Headers.Add("X-Frame-Options", "DENY");
    context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
    await next();
});
  

Use NWebSec for advanced headers.

11. Logging & Monitoring

  • Use Serilog/NLog for structured logging.

  • Monitor failed login attempts.

  • Never log sensitive data (passwords, tokens, credit cards).

12. Prevent Denial of Service (DoS) Attacks

ASP.NET Core 7 and later support built-in rate limiting.

  
    builder.Services.AddRateLimiter(_ => _
    .AddFixedWindowLimiter("fixed", options =>
    {
        options.Window = TimeSpan.FromSeconds(10);
        options.PermitLimit = 5;
    }));
  

Deploy a WAF (Web Application Firewall) in production.

Conclusion

Securing data in ASP.NET Core MVC applications requires a multi-layered approach.

  • Enforce HTTPS

  • Secure authentication & authorization

  • Protect configuration & secrets

  • Encrypt sensitive data

  • Prevent SQL Injection, XSS, and CSRF.

  • Harden cookies, sessions, file uploads, and headers

  • Enable logging, monitoring, and rate limiting

By following these practices, you’ll ensure your application complies with modern security standards and is resilient against common web vulnerabilities.