集群环境下,你不得不注意的ASP.NET Core Data Protection 机制

前言

最近线上环境遇到一个问题,就是ASP.NET Core Web应用在单个容器使用正常,扩展多个容器无法访问的问题。查看容器日志,发现以下异常:

1
warn: Microsoft.AspNetCore.Session.SessionMiddleware[7] Error unprotecting the session cookie. System.Security.Cryptography.CryptographicException: The key {3b046482-7cff-475b-b252-d12ab389d6c3} was not found in the key ring. For more information go to http://aka.ms/dataprotectionwarning at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData) at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

通过排查,发现了是由于 ASP.NET Core Data Protection 机制引起的。

ASP.NET Core Data Protection 机制

Data Protection(数据安全)机制:为了确保Web应用敏感数据的安全存储,该机制提供了一个简单、基于非对称加密改进的、性能良好的、开箱即用的加密API用于数据保护。
它不需要开发人员自行生成密钥,它会根据当前应用的运行环境,生成该应用独有的一个私钥。这在单一部署的情况下没有问题。
一旦在集群环境下进行水平扩展,那么每个独立的应用都有一个独立的私钥。这样在负载均衡时,一个请求先在A容器建立的Session会话,该机制会通过当前容器的密钥加密Cookie写入到客户端,下个请求路由到B容器,携带的Cookie在B容器是无法通过B容器的密钥进行解密。
进而会导致会话信息丢失的问题。所以在集群情况下,为了确保加密数据的互通,应用必须共享私钥

私钥共享

这里以使用Redis来共享私钥举例,添加Microsoft.AspNetCore.DataProtection.StackExchangeRedis Nuget包用于存储密钥。
添加Microsoft.Extensions.Caching.StackExchangeRedisNuget包用于配置分布式Session。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public IServiceProvider ConfigureServices(IServiceCollection services)
{

//获取Redis 连接字符串
var redisConnStr = this.Configuration.GetValue<string>(SigeAppSettings.Redis_Endpoint);
var redis = ConnectionMultiplexer.Connect(redisConnStr);//建立Redis 连接

//添加数据保护服务,设置统一应用程序名称,并指定使用Reids存储私钥
services.AddDataProtection()
.SetApplicationName(Assembly.GetExecutingAssembly().FullName)
.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");

//添加Redis缓存用于分布式Session
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConnStr;
options.InstanceName =Assembly.GetExecutingAssembly().FullName;
});

//添加Session
services.AddSession(options =>
{
options.Cookie.Name = Assembly.GetExecutingAssembly().FullName;
options.IdleTimeout = TimeSpan.FromMinutes(20);//设置session的过期时间
options.Cookie.HttpOnly = true;//设置在浏览器不能通过js获得该cookie的值
options.Cookie.IsEssential = true;
}
);
}