ASP.NET - Use of AppendCookie in case of Remember me checking

Asked By Rajashekar on 03-Aug-11 03:01 AM
How AppendCookie will be used in RememberMe checking in case of singing in into a site? 
How to handle the cookies to remember multiple users names and passwords if they checks the Remember me checkboxes.
Ravi S replied to Rajashekar on 03-Aug-11 03:04 AM
Hi

By default this feature is implemented using a cookie.

Do you see such a cookie in the Cookies folder? (on Vista C:\Users\Username\AppData\Roaming\Microsoft\Windows\Cookies)

If not, have you disabled cookies in your browser?

Kalit Sikka replied to Rajashekar on 03-Aug-11 03:05 AM
his is what you should never do, because it is very easy to change the value of a cookie and send back to server. Even storing "user is looged in as 'AAA' in a cookie is wrong, because I could then change it to "user is logged in as 'BBBB'.

In ASP.NET, use

FormsAuthentication.SetAuthCookie(username, true);

The second argument's value determines if the cookie is persistent (the remember me checkbox's value).

Ravi S replied to Rajashekar on 03-Aug-11 03:06 AM
HI

To handle the cookies to remember multiple users names and passwords

A good place to find some answers about cookies is http://www.cookiecentral.com/c_concept.htm For membership usually is used a cookie with a long string called 'token' that is issued from the website when you provide your user name and password. More about the process you can find in this http://jaspan.com/improved_persistent_login_cookie_best_practice. When using forms authentication in ASP.NET you can set the authentication cookie like this:

FormsAuthentication.SetAuthCookie(userName, isPersistanceCookie);

The second parameter is used for "Remember Me" functionality - if true it will create persistent cookies that will last after you leave the site. You can also programatically manipulate the cookie like this:

HttpCookie authCookie =
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
Jitendra Faye replied to Rajashekar on 03-Aug-11 03:08 AM

In order to create the "Remember Me" option, you need to use Cookies

//Create a cookie object and name it as usercredentials
HttpCookie usercredentialsCookie = new HttpCookie("usercredentials");

// to add to the cookie. the first time.
usercredentialsCookie.Values["username"] = txtUserName.Text;
usercredentialsCookie.Values["userpassword"] = txtPassword.Text;

//set an expiry
usercredentialsCookie.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(usercredentialsCookie);

You need to read it in the PageLoad event, like

//In your page load event, check the cookies and load it if required.

if (!Page.IsPostBack)
{
if (Request.Cookies["userLoginDetails"] != null)
{
txtUserName.Text = Server.HtmlEncode(Request.Cookies["usercredentials"].Values[0]).ToString();
txtPassword.Attributes.Add("value", Server.HtmlEncode(Request.Cookies["usercredentials"].Values[1]));
}
}

Hope this will help you.

Riley K replied to Rajashekar on 03-Aug-11 03:13 AM

At first, you should modify and check authentication mode of Web.config. It will play an important role around whole processes.

<authentication mode="Forms">
    <forms loginUrl="Default.aspx"
      protection="All"
      requireSSL="false"
      timeout="60"
      name=".SSOAUTH"
      path="/"
      cookieless="UseCookies"
      slidingExpiration="true" />
  </authentication>

You should notice the parameters path="/" and cookieless="UseCookies". You have to confie your limitation of cookie using path and you'd better explicitly define "UseCookie" unless you will get an endless transfer pages[1].

2. Issue Cookie

Once, login was successfule, you have to make IIS responses the login information to the client using cookie.

protected void Login1_LoggedIn(object sender, EventArgs e)
{
  if (Response.Cookies.Count > 0)
  {
     foreach (string s in Response.Cookies.AllKeys)
     {
      if (s == FormsAuthentication.FormsCookieName)
      {
       if (Login1.RememberMeSet == true)
       {
        // change the value to increase the cookies expiration by
        Response.Cookies[s].Expires = DateTime.Now.AddDays(1);
       }
      }
     }
  }
}


3. Execute Auto-login Using Cookie

ASP.NET has a reserved name for login cookie as like "__LOGINCOOKIE__". In this step, determine the validation of cookie and user information from the __LOGINCOOKIE__ as follows:


Add cookie handling source in the login page[5].
 
protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    try
    {
      // get login cookie and decrypt it.
      FormsAuthenticationTicket ticket =
        FormsAuthentication.Decrypt(Request.Cookies["__LOGINCOOKIE__"].Value);
      FormsIdentity id = new FormsIdentity(ticket);
      // extract user information.
      Context.User = new System.Security.Principal.GenericPrincipal(id, new string[0]);
      string user = Context.User.Identity.Name.ToString();
      // check validation.
      if (user != null && user.Length > 0 && ticket.Expired != true && ticket != null)
      {
        Response.Redirect("main.aspx"); // redirect to the main page.
      }
    }
    catch
    {
      // Decrypt method failed.
    }
  }
}

If your cookie was normal as accurate, you can see the main.aspx page without login process.

dipa ahuja replied to Rajashekar on 03-Aug-11 03:15 AM
Whenever a user will be online or login from your site, a separate cookie is generate for all the users. So you don't need to worry how to store multiple value, because all users are your different client and the cookie is saved in the client side that mean in the computer of the client machine.

and here is the code for "Remember Me" login..

<div>
  <asp:TextBox ID="TbUserName" runat="server"></asp:TextBox><br />
  <asp:TextBox ID="TbPassword" runat="server"></asp:TextBox><br />
  Remember Me:<asp:CheckBox ID="CbRememberMe" runat="server" />
</div>
<asp:Button ID="BtLogin" runat="server" Text="Button" OnClick="BtLogin_Click" /><br />
<asp:LinkButton ID="lbSignout" runat="server" Text="Sign Out"/>
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    //Check if the browser support cookies 
    if (Request.Browser.Cookies)
    {
      //Check if the cookies with name PBLOGIN exist on user's machine 
      if (Request.Cookies["PBLOGIN"] != null)
      {
        Response.Redirect("home.aspx");
          
      }         
    }
  }
}
protected void BtLogin_Click(object sender, System.EventArgs e)
{
  //check if remember me checkbox is checked on login 
  if ((this.CbRememberMe.Checked))
  {
    //Check if the browser support cookies 
    if ((Request.Browser.Cookies))
    {
      //Check if the cookie with name PBLOGIN exist on user's machine 
      if ((Request.Cookies["PBLOGIN"] == null))
      {
        //Create a cookie with expiry of 30 days 
        Response.Cookies["PBLOGIN"].Expires = DateTime.Now.AddDays(30);
        //Write username to the cookie 
        Response.Cookies["PBLOGIN"]["UNAME"] = this.TbUserName.Text;
        //Write password to the cookie 
        Response.Cookies["PBLOGIN"]["UPASS"] = this.TbPassword.Text;
      }
      //If the cookie already exist then wirte the user name and password on the cookie 
      else
      {
        Response.Cookies["PBLOGIN"]["UNAME"] = this.TbUserName.Text;
        Response.Cookies["PBLOGIN"]["UPASS"] = this.TbPassword.Text;
      }
    }
  }
 
  this.VerifyLogin(this.TbUserName.Text, this.TbPassword.Text);
}
 
protected void VerifyLogin(string UserName, string Password)
{
  try
  {
    if (TbUserName.Text == "dipa" && TbPassword.Text == "dipa")
    {
      Response.Redirect("home.aspx");
    }
    //If login credentials are correct 
    //Redirect to the user page 
    //else 
    //prompt user for invalid password 
    //end if
  }
  catch (System.Exception ex)
  {
    Response.Write(ex.Message);
  }
}
 
protected void lbSignout_Click(object sender, System.EventArgs e)
{
  //Check iIf the cookies with name PBLOGIN exist on user's machine 
  if ((Request.Cookies["PBLOGIN"] != null))
  {
    //Expire the cookie 
    Response.Cookies["PBLOGIN"].Expires = DateTime.Now.AddDays(-30);
  }
  //Redirect to the login page 
}
Radhika roy replied to Rajashekar on 03-Aug-11 11:34 AM
basically remind functionality will be implement in login page to save the user details. this can be implemented with the help of cookies. cookies will store in browser. 


http://asp.net/ is providing login controls along with remind me next time in built in option. any way here is the custom code for remind me next time. 

if (chkRememberPassword.Checked == true) 

Response.Cookies["UName"].Value = txtUName.Text; 
Response.Cookies["PWD"].Value = txtPWD.Text; 
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2); 
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2); 

else 

Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(-1); 
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(-1); 


Paste the following code snippet in page load 

if (!IsPostBack) 

if (Request.Cookies["UName"] != null) 
txtUName.Text= Request.Cookies["UName"].Value; 
if (Request.Cookies["PWD"] != null) 
txtPWD.Text.Attributes.Add("value", Request.Cookies["PWD"].Value); 
if (Request.Cookies["UName"] != null && Request.Cookies["PWD"] != null) 
chkRememberPassword.Checked = true; 



try his code snippet in your login page and defenitely you will get desired result