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)
Join the conversation! Your thoughts help the community grow.