ASP.NET Core数据保护通过AddDataProtection()配置,支持文件系统、Azure Key Vault、Redis和EF Core等多种密钥存储方式,确保多实例间加密解密一致性,适用于不同部署环境的安全需求。

ASP.NET Core中的数据保护,说白了,就是框架提供的一套用于保护敏感数据的API和机制。它能帮你把那些需要加密存储的数据(比如认证Cookie、CSRF令牌,或者你应用里任何需要保密的字符串)安全地加密、解密,并且还帮你管理这些加密密钥。这玩意儿省去了我们自己去折腾复杂的密码学细节,让开发者能更专注于业务逻辑,同时又确保了数据的安全。
配置ASP.NET Core的数据保护,通常从
Program.cs
Startup.cs
AddDataProtection()
// Program.cs var builder = WebApplication.CreateBuilder(args); // 添加数据保护服务 builder.Services.AddDataProtection(); // ... 其他服务注册 var app = builder.Build(); // ... 其他中间件配置 app.Run();
这样做了之后,ASP.NET Core会默认把加密密钥存储在文件系统里。具体位置嘛,通常是你的用户配置文件目录(比如
C:Users{username}AppDataLocalASP.NETDataProtection-Keys~/.aspnet/DataProtection-Keys
所以,更实际的配置是指定一个共享的密钥存储位置。这里有几个常见的选择:
1. 使用文件系统共享路径 (适用于简单的多实例,但仍有安全考量): 如果你在同一个网络共享存储上运行多个实例,可以指定一个共享文件夹。
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"\servershareDataProtectionKeys"));
// 确保这个目录对IIS进程或容器有读写权限2. 存储到Azure Key Vault (云原生首选,高度安全): 这是在Azure上部署应用时最推荐的方式。Key Vault不仅能存储密钥,还能管理密钥的生命周期,提供硬件安全模块(HSM)保护。
// 需要安装 NuGet 包:Microsoft.AspNetCore.DataProtection.AzureKeyVault
// 和 Azure.Extensions.AspNetCore.DataProtection.Keys
// 以及 Azure.Identity (用于身份验证)
using Azure.Identity;
using Azure.Security.KeyVault.Keys;
using Azure.Extensions.AspNetCore.DataProtection.Keys;
// ...
var keyVaultUri = new Uri(builder.Configuration["KeyVault:Uri"]); // 从配置中获取Key Vault URI
var client = new KeyClient(keyVaultUri, new DefaultAzureCredential());
builder.Services.AddDataProtection()
.PersistKeysToAzureKeyVault(client, "my-app-data-protection-key"); // "my-app-data-protection-key" 是Key Vault中的一个Key名称
// 或者你可以让它自动生成和管理密钥:
// .PersistKeysToAzureKeyVault(client);这里
DefaultAzureCredential
3. 存储到Redis (分布式缓存,容器化环境常见): 对于容器化部署,或者需要高性能、分布式共享密钥的场景,Redis是个不错的选择。
// 需要安装 NuGet 包:Microsoft.AspNetCore.DataProtection.StackExchangeRedis
using StackExchange.Redis;
// ...
var redisConnection = ConnectionMultiplexer.Connect(builder.Configuration["Redis:ConnectionString"]);
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redisConnection, "DataProtection-Keys"); // "DataProtection-Keys" 是Redis中的一个键前缀4. 存储到Entity Framework Core (数据库存储): 如果你已经在使用EF Core,并且想把密钥也存到数据库里,这也是个
以上就是ASP.NET Core中的数据保护是什么?如何配置?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号