2

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);
    }
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Sayantan Das
  • 73
  • 1
  • 1
  • 16
  • 5
    I wouldn't put the password in the cookie use another token (just username would suffice) - have a look here http://stackoverflow.com/questions/2452656/asp-net-mvc-rememberme – Shaun Wilde Dec 15 '13 at 09:21
  • 1
    You may use another SO answers, like this: http://stackoverflow.com/questions/5619791/implementing-remember-me-feature-in-asp-net-mvc – Boris Parfenenkov Dec 15 '13 at 09:24
  • Can u help me with the exact code..? – Sayantan Das Dec 15 '13 at 09:34
  • 1
    Your choice to store the password in the cookie is very, very, very bad: http://www.troyhunt.com/2013/07/how-to-build-and-how-not-to-build.html – jessehouwing Dec 15 '13 at 11:21

2 Answers2

4
 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..!!

Amarnath Balasubramanian
  • 9,300
  • 8
  • 34
  • 62
0

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

Roman Pushkin
  • 5,639
  • 3
  • 40
  • 58