CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Adding Remember Me Option in Login Form for Forms Authentication
Submitted By Satheesh Babu B
On 12/4/2008 6:34:42 AM
Tags: asp.net,C#,CodeDigest  

 

In the below code, the line where we are creating FormsAuthentication ticket we have an argument for specifying cookie as persistent or non persistent cookie. This attribute is the one that is used for "Remember Me" option in Login forms. Include a Checkbox beneath the password textbox in login page and assign the Checked property of the checkbox as the value for the above said argument.

 

I have included the whole Login click event for authenticating users.

 

protected void btnLogin_Click(object sender, EventArgs e)

    {

        User _user = new User();

        DBOperations dbo = new DBOperations();

        _user = dbo.CheckUser(txtUserid.Text);

        if (_user != null)

        {

            if (_user.Password == txtPassword.Text)

            {

                FormsAuthenticationTicket Authticket = new FormsAuthenticationTicket(

                                                        1,

                                                        txtUserid.Text,

                                                        DateTime.Now,

                                                        DateTime.Now.AddMinutes(30),

                                                        chkRememberMe.Checked,

                                                        _user.Role,

                                                        FormsAuthentication.FormsCookiePath);

               

                string hash = FormsAuthentication.Encrypt(Authticket);

 

                HttpCookie Authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

               

                if (Authticket.IsPersistent) Authcookie.Expires = Authticket.Expiration;

               

                Response.Cookies.Add(Authcookie);

 

                string returnUrl = Request.QueryString["ReturnUrl"];

                if (returnUrl == null) returnUrl = "/";

               

                Response.Redirect(returnUrl);

            }

            else

            {

                lblMessage.Text = "Password does'nt match.";

            }

        }

        else

        {

            lblMessage.Text = "User not exists.";

        }

    }

 

In the above code, chkRememberMe is the Checkbox id.

 

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..