Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Store User Password in Session cookie?

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.

Would it be possible to store the users password in this encrypted cookie as well. If so how would you access it server side?

I need the users username and password available server side because I need to call web services that use those same credentials. Is there some better way to do this?

like image 373
w.donahue Avatar asked Dec 27 '11 03:12

w.donahue


3 Answers

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.

like image 183
SLaks Avatar answered Oct 19 '22 19:10

SLaks


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).

like image 28
RickNZ Avatar answered Oct 19 '22 18:10

RickNZ


Not recommended but you can use FormsAuthenticationTicket.UserData.

like image 2
imran_ku07 Avatar answered Oct 19 '22 19:10

imran_ku07