ASP.NET Core 2.2 MVC 中的 IsAuthenticated 问题

Problem with IsAuthenticated in ASP.NET Core 2.2 MVC

我在使用 User.Identity.IsAuthenticated 时遇到了一个具体问题。 如果我在 Chrome 中打开一个新选项卡并进入我的环境,例如:https://localhost:5001,它会正常打开并将我重定向到主页(因为我已经登录)。

但是,如果我通过 link 打开网站,例如:我收到一封电子邮件,其中包含 link https://localhost:5001,如果我单击 link我刚刚重定向到登录屏幕。

但是因为我已经登录,正确的是重定向到主页,如果我按 f5,系统将我重定向到主页。

查看代码中的调试,在我的操作中,它表明 User.Identity.IsAuthenticated = false

现在当我按 f5 进行调试时 returns true

我的启动代码是这样的

    services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = "/Security/Login";
        options.LogoutPath = "/Security/Logout";
        options.AccessDeniedPath = "/Security/AccessDenied";
        options.SlidingExpiration = true;
        options.ExpireTimeSpan = TimeSpan.FromDays(15);

        options.Cookie = new CookieBuilder
        {
            HttpOnly = true,
            Name = ".CustomName",
            Path = "/",
            SameSite = SameSiteMode.Strict,
            SecurePolicy = CookieSecurePolicy.SameAsRequest,
            Expiration = TimeSpan.FromDays(15)
        };
    });

SameSite cookies explained

If you set SameSite to Strict, your cookie will only be sent in a first-party context. In user terms, the cookie will only be sent if the site for the cookie matches the site currently shown in the browser's URL bar. When the user is on your site, then the cookie will be sent with the request as expected. However when following a link into your site, say from another site or via an email from a friend, on that initial request the cookie will not be sent.

改用SameSiteMode.Lax。这将使浏览器包含一个身份验证 cookie,其中包含来自不同来源的链接,例如邮件。