【问题标题】:C# MVC 5 The ticket cookie is cleared when the form authentication signs outC# MVC 5 表单身份验证注销时清除票证cookie
【发布时间】:2017-09-02 12:59:27
【问题描述】:

我需要访问 cookie 以获取用户和密码,然后将它们设置在登录视图的文本框中,因为在该视图中选中了“记住我”。

注销方法

public ActionResult LogOff()
{
    //Session.Abandon();
    // sign out.
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Login");
}

成功登录后初始化会话和 cookie。

private void InitializeSessionVariables(AgentDTO user)
{
    // SessionModel.AgentId = user.ID;
    Response.Cookies.Clear();
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,user.MobilePhone,DateTime.Now,DateTime.Now.AddDays(30),true,"",FormsAuthentication.FormsCookiePath);
    // Encrypt the ticket.
    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
    // Create the cookie.
    HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Name of auth cookie (it's the name specified in web.config) // Hashed ticket
    authenticationCookie.Expires = DateTime.Now.AddDays(365);
    // Add the cookie to the list for outbound response
    Response.Cookies.Add(authenticationCookie);
}

登录视图的操作结果 我第一次注销然后尝试访问 cookie 时遇到问题,但它返回 null 因为我运行“FormsAuthentication.SignOut ();”

public ActionResult Index(LogonDTO model, string message = null, string reason = null)
{
    if (SessionModel.AgentMobilePhone != null) return RedirectToAction("Index", "Home");
    if (reason != null) message = "Su sessión ha expirado. Vuelva a loguearse.";
    ViewBag.Message = message;

    if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        model.Username = authTicket.Name;
        //model.Password = "in progress..."
    }
    return View(model);
}

【问题讨论】:

  • 根据本文:support.microsoft.com/en-us/help/910443/…FormsAuthentication.SignOut(); 无论如何都会删除 cookie。我假设在持久性 cookie 的情况下,您根本不会调用 FormsAuthentication.SignOut();
  • 那么,在我的情况下,我不应该清理 cookie 吗?
  • 我相信 FormsAuthentication.SignOut(); 只有在用户仍然有票证/cookie 但您的服务器上没有打开的会话时才应该使用。这将从用户的浏览器中删除票证并强制他再次“登录”。

标签: c# asp.net-mvc asp.net-mvc-5 formsauthentication formsauthenticationticket


【解决方案1】:

如果他点击记住我复选框,您可以使用 javascript 来存储用户信息

使用

localStorage.setItem("UserName", "Smith");

设置值

并在登录页面上的 Jquery 文档就绪事件上写下代码

var UserName = localStorage.getItem("UserName");
if (UserName) $("#username").val(UserName);

希望这能解决您的问题。

【讨论】:

  • 在本地存储中我无法保存密码。
  • 使用 SessionID 在服务器端存储密码。您可以向服务器发送带有 SessionID 的请求,服务器将获取针对该用户存储的用户信息并允许用户登录。
  • 不建议将其保留在会话中。它必须在 cookie 中,因为今天或明天进入应用程序时,如果选中记住我,则应将用户和密码放在文本框中。如果我第二天打开应用程序或关闭应用程序,会话将终止。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 2016-05-30
相关资源
最近更新 更多