Introduction
In modern web applications, data security is critical, especially when dealing with sensitive information such as authentication cookies, tokens, or personal user data. ASP.NET Core provides a Data Protection API that allows developers to encrypt and protect data in a consistent and secure way.
By default, ASP.NET Core stores cryptographic keys in the file system. However, in production scenarios, especially for load-balanced environments or multiple server instances, it is recommended to store keys in a centralized and secure location. One such option is SQL Server, which allows:
In this guide, we will show step-by-step how to configure ASP.NET Core Data Protection with SQL Server for a production-ready setup.
1. Understanding ASP.NET Core Data Protection
ASP.NET Core Data Protection provides:
Key management – Automatic creation, rotation, and storage of keys.
Encryption and decryption – Protect sensitive data such as cookies, tokens, or view state.
Isolation – Keys are unique per application unless shared intentionally.
Common use cases
Protecting authentication cookies
Encrypting tokens for password reset links
Storing sensitive session data
2. Installing Required Packages
To use SQL Server as a key store, install:
dotnet add package Microsoft.AspNetCore.DataProtection.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
3. Setting Up SQL Server Table
Create a table for storing data protection keys. You can do this using EF Core migrations.
3.1 Define the Key Entity
using Microsoft.AspNetCore.DataProtection.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class DataProtectionKeyContext : DbContext, IDataProtectionKeyContext
{
public DataProtectionKeyContext(DbContextOptions<DataProtectionKeyContext> options)
: base(options) { }
public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
}
3.2 Add Migration and Update Database
dotnet ef migrations add AddDataProtectionKeys
dotnet ef database update
This creates the table DataProtectionKeys in SQL Server.
4. Configuring Data Protection to Use SQL Server
In Program.cs or Startup.cs:
builder.Services.AddDbContext<DataProtectionKeyContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDataProtection()
.PersistKeysToDbContext<DataProtectionKeyContext>()
.SetApplicationName("MyApp") // Important for multi-server scenarios
.ProtectKeysWithCertificate("thumbprint-of-your-certificate"); // Optional: encrypt keys
Key Points
PersistKeysToDbContext – Stores keys in SQL Server instead of the file system.
SetApplicationName – Ensures all instances of the app share the same key ring.
ProtectKeysWithCertificate – Optional, adds an extra encryption layer using an X.509 certificate.
5. Optional: Protect Keys with Certificate
For extra security, you can protect keys using a certificate:
builder.Services.AddDataProtection()
.PersistKeysToDbContext<DataProtectionKeyContext>()
.ProtectKeysWithCertificate(
new X509Certificate2("path-to-certificate.pfx", "certificate-password"));
6. Using Data Protection in ASP.NET Core
6.1 Encrypting and Decrypting Data
Inject IDataProtector into your service or controller:
public class SensitiveDataService
{
private readonly IDataProtector _protector;
public SensitiveDataService(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("SensitiveData.V1");
}
public string Protect(string input)
{
return _protector.Protect(input);
}
public string Unprotect(string input)
{
return _protector.Unprotect(input);
}
}
Usage
var service = new SensitiveDataService(provider);
string protectedValue = service.Protect("my-secret-value");
string originalValue = service.Unprotect(protectedValue);
6.2 Protecting Cookies
ASP.NET Core authentication cookies use Data Protection by default. Using SQL Server as a key store ensures that cookies are valid across multiple instances.
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "MyAppAuth";
options.LoginPath = "/Account/Login";
options.SlidingExpiration = true;
});
7. Multi-Server / Load-Balanced Environment
Using SQL Server for Data Protection keys is essential for load-balanced scenarios:
All servers read/write keys from a central database.
No need to synchronize file systems.
Automatic key rotation works across servers.
Tip: Always use SetApplicationName to ensure all servers share the same key ring.
8. Angular Integration
In Angular applications:
You do not directly use Data Protection, as it's backend-specific.
However, tokens and cookies protected by ASP.NET Core can be safely used in Angular.
For example:
// Angular HttpClient automatically sends cookies if withCredentials is truethis.http.get('/api/secure-data', { withCredentials: true });
9. Key Management Best Practices
Rotate keys regularly – Data Protection handles automatic rotation.
Back up SQL Server – Ensure you can restore keys in case of disaster.
Use certificate protection – Adds an extra security layer.
Set ApplicationName consistently – Required for multiple environments or servers.
Monitor key expiration – Ensure old keys are not removed prematurely.
10. Advantages of SQL Server Key Storage
| Feature | Benefit |
|---|
| Centralized keys | Works across multiple servers |
| Database backups | Keys are safely backed up automatically |
| Certificate protection | Extra encryption layer |
| Automatic rotation | No manual intervention required |
| Multi-application support | Multiple apps can share the same key ring if needed |
11. Optional Enhancements
Use Azure Key Vault instead of SQL Server for cloud deployments.
Logging key usage for auditing purposes.
Environment-specific keys – Different keys for dev, staging, and production.
Integration with IdentityServer – Protect tokens in centralized identity scenarios.
Conclusion
ASP.NET Core Data Protection provides a robust mechanism to encrypt sensitive data. Using SQL Server as a key store is a production-ready approach that ensures:
Shared key access across multiple servers
Secure, recoverable key storage
Seamless integration with authentication cookies and tokens
By following this approach, you can:
Secure sensitive data in enterprise applications
Support load-balanced or multi-instance deployments
Maintain strong encryption and automatic key rotation
Key takeaways
Store Data Protection keys in SQL Server for multi-server environments.
Optionally encrypt keys using X.509 certificates.
Use IDataProtector for custom encryption needs.
Ensure proper backups and rotation policies.
This setup is ideal for enterprise-grade applications, secure web APIs, and production-ready deployments.