There is a popular option in login page i.e Remember me. If we check Remember me, it remembers login-id and password after logging out from the website. Also when Remember me is not checked, it work as a normal control... means it does not remember the login-id or password after exit the website.
When Remember me is checked, it simply saves the login credentials (of course valid one) into the browser in form of cookie.
So after successful login, credentials is written into cookie. Also after logout, cookie is not destroyed and is added to the http response. It is tracked at the login page and login-id and password is set.
After checking the credential call this method...
public void WriteCredentials() {
HttpCookie cookie = new HttpCookie("Login_Credentials");
if (chkRememberMe.Checked)
{
cookie.Values.Add("user_name", txtUserName.Text);
cookie.Values.Add("user_password", txtPassword.Text);
cookie.Expires.AddDays(30); //Cookie will expire after 30 days.
}
else
{
cookie.Values.Add("user_name", string.Empty);
cookie.Values.Add("user_password", string.Empty);
cookie.Expires.AddMinutes(2); //Cookie with empty credential strings.
}
Response.Cookies.Add(cookie); //Finally cookie is added to the http response.
}
Add following code-snips in Sign-out function...
if (Response.Cookies["Login_Credentials"] != null) {
HttpCookie cookie = Request.Cookies.Get("Login_Credentials");
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);
}
Now after singing out, again cookie is added to the response. It will be tracked in login page at Page Load...
if(!IsPostPack)
{
//Remember me...
if (Request.Cookies["Login_Credentials"] != null)
{
HttpCookie cookie = Request.Cookies.Get("Login_Credentials");
txtUserName.Text = cookie.Values["user_name"];
//Notice that how the value of password is set.
txtPassword.Attributes.Add("value", cookie.Values["user_password"]);
if (txtUserName.Text != "")
chkRememberMe.Checked = true;
else
chkRememberMe.Checked = false;
}
}
This code is again a tested one.
No comments:
Post a Comment