首页 > 解决方案 > ASP.Net OWIN 设置 Cookie 但用户立即注销

问题描述

我已经有这个问题几个月了。这个问题是零星的并且难以重现,但我设法找到了一种有点一致的方法来解决它。我正在调试,发现一旦它应该重定向到 /home/index,它就会转到 /account/logoff。如果我在本地进行测试,那么它将在第一次登录时正常工作,如果我使用其他帐户,它将失败。在看到一些与它们相关的帖子后,我设置了 CookieName 和 CookieSecure。但这似乎没有帮助。

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            CookieManager = new SystemWebChunkingCookieManager(),
            CookieName = "NewImprovedCookieName",
            CookieSecure = CookieSecureOption.SameAsRequest,
            LoginPath = new PathString("/Account/Login"),
            LogoutPath = new PathString("/Account/LogOff"),
            Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
        });

LogOff 发生在此处的最后一行代码之后。

private ActionResult RedirectToLocal(string returnUrl)
{
    if (Url.IsLocalUrl(returnUrl))
    {
        return Redirect(returnUrl);
    }
    return RedirectToAction("Index", "Home");
}

我尝试更新项目中的所有内容以查看它是否是某个已修复的错误(这是一个旧项目),但似乎没有任何帮助。

有没有办法解决这个问题,还是我应该考虑迁移到 .Net Core?

标签: authenticationcookiesasp.net

解决方案


我不知道这是否是最好的解决方案,但我确实找到了一个有效的解决方案。我注意到 SessionID 在注销后仍然存在。我添加了代码以删除放弃会话并更改会话 ID,它现在似乎正在工作。

    public ActionResult LogOff()
    {
        AuthenticationManager.SignOut();
        Session.Clear();
        Session.Abandon();
        Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
        return RedirectToAction("Index", "Home");
    }

推荐阅读