ASP.NET Core  

Using ASP.NET Core Data Protection with SQL Server

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:

  • Sharing cryptographic keys across multiple servers

  • Ensuring consistency and recoverability

  • Centralized management

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:

  1. Key management – Automatic creation, rotation, and storage of keys.

  2. Encryption and decryption – Protect sensitive data such as cookies, tokens, or view state.

  3. 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
  • DataProtection.EntityFrameworkCore provides the SQL Server backing store.

  • EntityFrameworkCore.SqlServer is needed to connect to the database.

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; }
}
  • DataProtectionKey is provided by Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.

  • IDataProtectionKeyContext is required for EF Core key storage.

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"));
  • This ensures that even if the database is compromised, the keys are encrypted.

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;
    });
  • Key rotation is handled automatically.

  • Multiple servers reading from the same SQL Server table can validate cookies correctly.

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 });
  • The backend will decrypt and validate the cookie using SQL Server-backed keys.

9. Key Management Best Practices

  1. Rotate keys regularly – Data Protection handles automatic rotation.

  2. Back up SQL Server – Ensure you can restore keys in case of disaster.

  3. Use certificate protection – Adds an extra security layer.

  4. Set ApplicationName consistently – Required for multiple environments or servers.

  5. Monitor key expiration – Ensure old keys are not removed prematurely.

10. Advantages of SQL Server Key Storage

FeatureBenefit
Centralized keysWorks across multiple servers
Database backupsKeys are safely backed up automatically
Certificate protectionExtra encryption layer
Automatic rotationNo manual intervention required
Multi-application supportMultiple 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

  1. Store Data Protection keys in SQL Server for multi-server environments.

  2. Optionally encrypt keys using X.509 certificates.

  3. Use IDataProtector for custom encryption needs.

  4. Ensure proper backups and rotation policies.

This setup is ideal for enterprise-grade applications, secure web APIs, and production-ready deployments.