问题描述
我有一个 ASP.NET Core 3.1 应用程序,它使用 cookie 身份验证并在 Web 场上运行。 我希望应用程序在 Web 服务器之间共享经过身份验证的 cookie。 问题是当我通过负载平衡器登录服务器 A 时,来自服务器 B 的下一个 ajax 请求重定向回登录页面。 (状态代码 302,设置 Cookie:.AspNet.SharedCookie=;)
如果我直接登录到服务器 A 并导航页面 - 它工作正常。所以我怀疑服务器 B 不验证服务器 A 生成的 cookie。 这是数据保护的配置:
services.AddDataProtection(options =>
{
options.ApplicationDiscriminator = "MyApp";
})
.PersistKeysToFileSystem(new DirectoryInfo(GetKeysPath()))
.SetApplicationName("MyApp")
.SetDefaultKeyLifetime(TimeSpan.FromDays(365));
和身份验证:
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/Login/Login";
options.LogoutPath = "/Login/Logout";
options.ReturnUrlParameter = "returnUrl";
options.Cookie.Name = ".AspNet.SharedCookie";
options.Cookie.Path = "/";
options.Cookie.IsEssential = true;
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
});
有人知道我错过了什么吗?
P.S.我在使用 DataProtection 时遇到的最初问题,每个服务器都生成了自己的密钥,因此其他服务器无法解密 cookie 和防伪令牌。所以我将相同的密钥文件复制到每个服务器,问题就消失了。
我使用的链接:
Share Cookies Between Applications
解决方法
我找到了问题的根本原因,问题不在于数据保护、身份验证或 Cookie。 问题在于会话,它使用内存来存储会话,因此其他服务器(创建的除外)对会话一无所知。所以我在数据库中添加了存储会话,如下所示:
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString =
_config["DistCache_ConnectionString"];
options.SchemaName = "dbo";
options.TableName = "TestCache";
});
最后,我的网络农场运行良好。