c# - 确保表单例份验证在浏览器关闭时注销

标签 c# asp.net c web-applications

我的 asp.net 网络应用程序和 Chrome 有问题。当我关闭 Chrome 浏览器窗口时,它不会清除 cookie。这意味着如果我使用表单例份验证登录我的 Web 应用程序,然后关闭并重新打开浏览器窗口,它会显示我仍然登录!

我读到这可能是一个 Chrome 错误,但肯定有某种解决方法。

我找到了 this发布并希望在浏览器窗口关闭时从中运行以下代码:

FormsAuthentication.SignOut();
Session.Abandon();

// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);

// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);

我的问题是,是否有我可以在代码中指定的浏览器关闭事件处理程序?也许 Application_End 在 Global.aspx 文件中?或者这不是它的本意?

或者有其他方法可以解决这个问题吗?

谢谢。

这是我的代码:

private void Login_Click(Object sender, EventArgs e)
  {
    // Create a custom FormsAuthenticationTicket containing
    // application specific data for the user.

    string username     = UserNameTextBox.Text;
    string password     = UserPassTextBox.Text;
    bool   isPersistent = false;

    if (Membership.ValidateUser(username, password))
    {
      string userData = "ApplicationSpecific data for this user.";

      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
        username,
        DateTime.Now,
        DateTime.Now.AddMinutes(30),
        isPersistent,
        userData,
        FormsAuthentication.FormsCookiePath);

      // Encrypt the ticket.
      string encTicket = FormsAuthentication.Encrypt(ticket);

      // Create the cookie.
      Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

      // Redirect back to original URL.
      Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
    }
    else
    {
      Msg.Text = "Login failed. Please check your user name and password and try again.";
    }
  }

仅将 isPersistent 替换为 checkbox.Checked 的值,默认情况下为 false

编辑:

可能发生的另一件烦人的事情来自 [this] 链接,其中 HitTest 门的答案是:

您使用的浏览器也很重要。 Chrome 具有在后台运行的能力,这会保持 session Cookie 一直存在,直到达到超时为止——当浏览器关闭时它们不会被丢弃(我很难发现这一点)。

2

最佳答案

没有浏览器关闭处理程序,怎么可能有?页面完成服务后,连接将关闭。您不知道用户是离开网站浏览、关闭浏览器,还是让它在那里停留一天。您将不得不使用客户端代码来调用服务来处理此问题,而执行此操作的客户端代码不够可靠,以至于无法使用。

设置身份验证 cookie 时,请确保持久性选项为 false。

此外,当您关闭浏览器时,请确保关闭所有浏览器窗口。如果您有多个浏览器窗口,它们将共享相同的 cookie 缓存,因此诸如 session cookie 之类的东西仍然存在,并让您相信身份验证由服务器保持事件状态,而实际上是浏览器。

关于c# - 确保表单例份验证在浏览器关闭时注销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25960148/

相关文章:

C 程序 - 求 2 的指数的最简单方法是什么

c - 图邻接表实现(C)

c++ - 定义 BLECharacteristic 时 Genuino 101 不运行

c# - 使用属性和 ServiceStack.Text.JsonSerializer 的自定义序列化

c# - 在文本框中显示 SQL 表的查询

java - 3DES 程序从 C# 转换为 Java 后的不同结果

javascript - 我该如何处理我的文本框自动完成功能?

c# - 如何从代码中隐藏一个 div (c#)

c# - 在 asp.net 中使用 dropzone.js

c# - 如何在 .NET 中获取给定字符串的单向哈希?