in the login control event loggedIn
protected void LoginControl_OnLoggedIn(object sender, EventArgs e)
{
CheckBox cb = LoginControl.FindControl("RememberMe") as CheckBox;
if (cb != null && cb.Checked)
{
string userData = "keep user login";
// true if a durable cookie (a cookie that is saved across browser sessions) was issued; otherwise, false.
bool isPersistent = false;
string username = LoginControl.UserName;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddYears(1),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
//Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// Create the cookie.
HttpCookie cook = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
cook.Expires = DateTime.Now.AddYears(1); // if not set the expire date, the cookie will removed after browser closed
Response.Cookies.Add(cook);
}
}
// get the how many minutes total and left to logout, form authentication
public class FormsAuthenticationHelper
{
public static double GetFormTimeout(Page page)
{
HttpCookie cookie = (HttpCookie)(page.Request.Cookies[FormsAuthentication.FormsCookieName]);
// if no user login, the cookie will be null
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
double timeoutInMinutes = (ticket.Expiration - ticket.IssueDate).TotalMinutes;
return timeoutInMinutes;
}
return -1;
}
public static double GetTotalLeftFormTimeout(Page page)
{
HttpCookie cookie = (HttpCookie)(page.Request.Cookies[FormsAuthentication.FormsCookieName]);
// if no user login, the cookie will be null
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket.Expiration - DateTime.Now > 0)
{
double timeoutMillisecond = (ticket.Expiration - DateTime.Now).TotalMilliseconds;
return timeoutMillisecond;
}
}
return -1;
}
}
// how to use
double currentTimeout = FormsAuthenticationHelper.GetFormTimeout(this.Page);
if (currentTimeout <= 60 * 24 * 30 && currentTimeout > -1) // if the page has timeout in a month
your function();