ASP.Net Store User Password in Session cookie?

前端 未结 3 1668
情书的邮戳
情书的邮戳 2021-01-18 08:10

I know the Membership provider stores the user name and an expiration time in an encrypted cookie and then uses that to verify the user is still logged in for a session.

3条回答
  •  天涯浪人
    2021-01-18 08:59

    Yes, you can do that. You pass the encoded info in the userData field of the FormsAuthenticationTicket constructor:

      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(version,
        name, issueDate, expirationDate, isPersistent, yourEncodedData);
      string secureTicket = FormsAuthentication.Encrypt(ticket);
      Response.Cookies.Add(
          new HttpCookie(FormsAuthentication.FormsCookieName, secureTicket));
    

    Ideally, this should be done over an SSL connection, and the ticket cookie should be marked with both the HttpOnly and Secure attributes.

    Then, to retrieve the value:

    FormsIdentity id = (FormsIdentity)User.Identity;
    FormsAuthenticationTicket ticket = id.Ticket;
    string yourEncodedInfo = ticket.UserData;
    

    You could also just set your own cookie, separate from the forms auth ticket.

    However, storing a password directly in a cookie, even if encrypted, is not a good idea from a security perspective. Instead, use Session state:

    Session["password"] = password;
    

    Session state also uses a cookie, but the cookie itself only contains a key. The server uses the key to obtain a dictionary of key/value pairs unique to that session, which stay on the server (or get serialized to the DB, depending on how it's configured).

提交回复
热议问题