"Remember me" functionality in a Login form

16.1k views Asked by At

I am using linq to entity connection. I want to keep user logged in once he entered into his account, This is my code. It's not working. Help, please

    if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
    {
        HttpCookie cookie = new HttpCookie(TxtUserName.Text, TxtPassword.Text);
        cookie.Expires.AddYears(1);
        Response.Cookies.Add(cookie);
    }
2

There are 2 answers

3
Amarnath Balasubramanian On BEST ANSWER
 if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
 {
    int timeout = rememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
    var ticket = new FormsAuthenticationTicket(TxtUserName.Text, TxtPassword.Text);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);// Not my line
    cookie.HttpOnly = true; // cookie not available in javascript.
    Response.Cookies.Add(cookie);
}

Go to your web.config and find the authentication element. You can set the cookie expiration time (in minutes) there, like such:

<system.web>
    <authentication mode="Forms">
        <forms loginUrl="~/Account/Login" 
               name="myCookie"                  <!-- optional, if you want to rename it -->
               timeout="2880" />                <!-- expires in 48 hours -->
    </authentication>
</system.web>

Source: how to apply "Remember Me" in c#

Hope this helps

Happy Coding..!!

0
Roman Pushkin On

I recommend to use MembershipReboot for authentication purposes in your app (samples are included).