ASP.Net Store User Password in Session cookie?

前端 未结 3 1645
情书的邮戳
情书的邮戳 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:48

    You should store it in session state, which never leaves the server.

    You should also try to change those web services to use authentication tickets instead of passwords (eg, OAuth), because it's never a good idea to store passwords in plain text.

    0 讨论(0)
  • 2021-01-18 08:52

    Not recommended but you can use FormsAuthenticationTicket.UserData.

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题