【问题标题】:Persistent Auth cookie in .net core 2.0.net core 2.0 中的持久身份验证 cookie
【发布时间】:2018-05-13 11:36:26
【问题描述】:

最近我在 .net core 2.0 中创建了我的新网站,并在身份验证中使用了持久 cookie。我还在为语言使用持久文化 cookie。

我的网站托管在 azure 共享池中,我没有指定任何机器密钥

问题。 当我在几个小时不活动(新浏览器)后重新打开我的网站时,我丢失了我的身份验证 cookie,我需要再次登录,但文化 cookie 按照上次会话工作。

我还设置了 Application Insights 可用性 以保持我的应用程序预热(每 10 分钟从 2 个不同位置对网站进行 ping 操作)。

登录控制器

if (this.accountService.ValidateOTP(phoneNumber, otp))
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.MobilePhone, phoneNumber),
                new Claim(ClaimTypes.Name, phoneNumber)
            };
            var userIdentity = new ClaimsIdentity("Custom");
            userIdentity.AddClaims(claims);
            ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);

            //await HttpContext.SignOutAsync("AnimalHubInstance");
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                userPrincipal,
                new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTime.Now.AddYears(1),
                });
}

启动

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(option =>
            {
                option.LoginPath = new PathString("/Account/Unauthorized");
                option.LogoutPath = new PathString("/Account/Logout");
                option.Cookie.Name = ".myAuth";
                option.ExpireTimeSpan = TimeSpan.FromDays(365);
                option.Cookie.Expiration = TimeSpan.FromDays(365);
            });

【问题讨论】:

  • 我注意到身份验证和文化 cookie 用于本地主机。仅当您的应用程序部署到 azure Web 应用程序时才会出现此问题?您也可以configure data protection 或将您的定价层级提高到基本或更高以缩小此问题。此外,您可以启用 始终开启 功能以保持您的应用程序始终处于加载状态,并且您的网络应用程序需要在基本或标准模式下,您可以关注here的详细信息。
  • @BruceChen 现在我不能使用基本或更高版本。我认为这个问题只会出现在 Azure 上(现在我正在创建新实例以挖掘更多细节)。我设置 Application Insights 可用性以使我的站点保持警告状态。重启后,我的应用程序仍在工作(保持登录并保持文化)

标签: .net azure asp.net-core asp.net-core-mvc


【解决方案1】:

您需要使用data protection 来保存您的会话加密密钥。

当在 Azure 应用服务或 IIS 中托管应用时(在 VM 中或本地),IIS 将在不活动时回收应用和应用池。因此,如果您的应用程序在特定时间内没有受到攻击,它将被关闭并在下一次连接时重新启动。

发生这种情况时,将为会话生成新的加密密钥,您之前的会话将无效。

【讨论】:

  • 我部分同意你的看法。但我设置了“Application Insights 可用性”来预热我的应用程序(每 10 分钟从 2 个不同位置 ping 网站)。我也要去试试数据保护api...
【解决方案2】:

当我在几个小时不活动(新浏览器)后重新打开我的网站时,我丢失了我的身份验证 cookie,我需要再次登录,但文化 cookie 可以按照上次会话工作。

您的文化 cookie 的值只是 urlencoded。正如 Tseng 所说,用于散列和加密的机器密钥可能会在某些时候自动重新生成。我认为这个问题是由您选择的定价层引起的。对于 免费共享 层,您的应用程序将在共享基础架构上运行,并且您只有有限的资源(例如 CPU 时间、RAM、磁盘空间)并且没有 SLA

App Service limits:

此外,我尝试重新启动网站并在本地回收应用程序池,身份验证cookie仍然可以按预期工作。对于我在基本定价层下的网络应用托管,直到现在我才遇到这个问题。

【讨论】:

    猜你喜欢
    • 2018-02-24
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    相关资源
    最近更新 更多