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?
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.
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).
Not recommended but you can use FormsAuthenticationTicket.UserData.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With