前言
在ASP.NET Core
中的Session
该如何存储?本文介绍了Session
信息在单个应用实例和多个应用实例中的不同存储方式,以及ASP.NET Core
在Session
数据安全方面做的一些努力。
TL;DR
在ASP.NET Core
中使用分布式缓存存储会话时,仅仅将Session
进行分布式存储还不够,由于ASP.NET Core
的数据安全保护机制,还需要将Data Protection
所使用的加密密钥也进行分布式存储,这样才能正确解密Cookies
:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration {
get; }
public void ConfigureServices(IServiceCollection services)
{
//将数据保护的秘钥存储为分布式,否则多个实例会有多个秘钥加密cookie值,导致即使读取到客户端的cookie也无法解密
services.AddDataProtection().PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect($"localhost:6379,defaultDatabase=0"), "DataProtection-Keys");
//添加reidis作为分布式缓存
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = $"localhost:6379,defaultDatabase=0";
});
//注册Session
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
})