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:

  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

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

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:

Tip: Always use SetApplicationName to ensure all servers share the same key ring.

8. Angular Integration

In Angular applications:

// Angular HttpClient automatically sends cookies if withCredentials is truethis.http.get('/api/secure-data', { withCredentials: true });

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

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:

By following this approach, you can:

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.