How do I Keep a user logged in for 2 weeks?
Add a hash key or a random string to both the cookie and the database (both the same key). If the cookie and database value are the same, when the user starts a new session, sign him/her in again. When the user reaches the two weeks, remove the secret key from the database using a cronjob (Unix) or scheduled task (Windows).
Warning: Do not rely on the cookie expire date, since people can hack their browser.
Rule: NEVER, EVER trust ANY of your users!
You can set the global session timeout (the value is in minutes) in web.config eg.
<system.web>
<authentication mode="Forms">
<forms timeout="20160"/>
</authentication>
</system.web>
This will be for all authenticated users. If you want to use the 'Remember Me' functionality then you will need to write your own code to set the cookie/ticket. Something like this (taken from here):
protected void Page_Load()
{
if (Request.Cookies["username"] == null || Request.Cookies["username"].Value.ToString().Trim() == "")
{
Login1.RememberMeSet = true;
}
else
{
Login1.UserName = Request.Cookies["username"].Value.ToString().Trim();
Login1.RememberMeSet = true;
}
}
protected void RememberUserLogin()
{
// Check the remember option for login
if (Login1.RememberMeSet == true)
{
HttpCookie cookie = new HttpCookie("username");
cookie.Value = Login1.UserName.Trim();
cookie.Expires = DateTime.Now.AddHours(2);
HttpContext.Current.Response.AppendCookie(cookie);
Login1.RememberMeSet = true;
}
else if (Login1.RememberMeSet == false)
{
HttpContext.Current.Response.Cookies.Remove("username");
Response.Cookies["username"].Expires = DateTime.Now;
Login1.RememberMeSet = false;
}
}
Just use a simple cookie with 2 weeks expiration date.