You can put user security token, IP address and timestamp in the line. Encrypt the string using a symmetric algorithm such as AES and place it as a cookie. Then change your code to read from the cookie. You can verify that the IP address in the cookie matches the IP address of users, this will prevent someone from stealing the cookie value and reproducing it. Here is the MSDN documentation for AES (Rjindael's original name). In this scheme, the token does not expire before the cookie and / or your timeout expire. I highly recommend that you set a timeout and not make it permanent or permanent, this will make the circuit less secure to exclude a timeout. Also put a timestamp at the beginning of your cookie value, because of the CBC mode on these algorithms, this will affect how the encrypted string looks like due to changes in bits at the beginning (avalanche effect).
The ASP.NET Membership Provider also has an authentication cookie, so this cookie should not expire before the membership cookie. Sessions time out because there is no guarantee that the user still exists, since HTTP is stateless, while the cookie is under the user's control and is sent every time the request is made.
getUsr function
protected UserData getUsr() { try { UserData usr = new UserData(); string token = Request.Cookies["secToken"].Value; // implement RijndaelManaged encryption/decryption scheme // this can also be serialized as an object to make cleaner var tokenValues = Decrypt(token).Split(','); // The timeout expired if (DateTime.Now > DateTime.Parse(tokenValues[1])) { throw new Exception("Timeout"); } // someone stole this cookie or is on a different internet connection if (tokenValues[0] != System.Web.HttpContext.Current.Request.UserHostAddress) { throw new Exception("Invalid IP"); } // You're ok everything checks out usr.SecurityToken = tokenValues[3].ToString(); MembershipUser mvcUser = Membership.GetUser(HttpContext.Current.User.Identity.Name); usr.Id = (int)mvcUser.ProviderUserKey; return usr; } catch (Exception ex) { log.Debug("Could not create usr object", ex); throw new Exception("Could not authenticate"); } }
source share