How to create login form/page and implement remember me next time checkbox in asp.net

Introduction: In this article i am going to explain How to implement remember me next time checkbox option along with username and password in the Log in form in asp.net using both C# and VB.net language. Username and password will be stored in the cookie .

remember me next time checkbox option in login form in asp.net

Description: The benefits of implementing remember me option is that user needs not to enter the username and password each time to log in, if he wish. This option will maintain the credentials i.e. username and password for the user when he visit the website next time.

In previous related article i explained How to create Login page/form and check username,password in asp.net using sql server database and Create registration form and send confirmation email to activate account to new registered users and  Create Change password form/page in asp.net using Sql server and Encrypt and decrypt username,password and store in Sql Server database and Create contact us form and Recover and reset the forgot password using activation link in email id and  Check login in asp.net by passing parameter to stored procedure in sql server .

The process is as follows: 
  • When user enter username and password and press the login button, the code will first verify the credentials from the Sql server database.
  • If verified then it will further check whether the "remember me next time" checkbox is checked or not. If checked then the username and password will be stored in the cookie for 30 days otherwise it will destroy the cookie by setting the cookie's expiration date to past date. E.g. one day in the past.
  • On page load event we check for the existence of cookie. If exists, username and password will be fetched from the cookie and filled in corresponding TextBox.

Implementation: Let's create a sample website to understand the concept. 
  • In the <form> tag of the design page (.aspx) place two TextBox controls, a CheckBox and a Button control. 

HTML Source Code:

<div>
    <fieldset style="width:320px;">
    <legend>Login with remember me option in asp.net</legend>   
    <table>
    <tr>
    <td>UserName : *</td><td>
        <asp:TextBox ID="txtUserName" placeholder="User Name" Width="180px" runat="server"></asp:TextBox><br />
        <asp:RequiredFieldValidator ID="rfvUserName" runat="server"
            ControlToValidate="txtUserName" Display="Dynamic"
            ErrorMessage="Please enter User Name" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
    <td>Password : *</td><td>
        <asp:TextBox ID="txtPwd" placeholder="Password" TextMode="Password" Width="180px" runat="server"></asp:TextBox><br />
        <asp:RequiredFieldValidator ID="rfvPwd" runat="server"
            ControlToValidate="txtPwd" Display="Dynamic"
            ErrorMessage="Please enter Password" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
    <td></td><td>
        <asp:Button ID="btnLogin" runat="server" Text="Login"
            onclick="btnLogin_Click" />
        <asp:CheckBox ID="chkRemember" Text="Remember me next time" runat="server" />
        </td>
    </tr>
    </table>
    </fieldset>   
    </div>

Note: I have also validated the username and password using RequiredFieldValidator validation control so that they can't be left blank.

  • Create a database in Sql server e.g. "MyDataBase" and in this database create a table with the columns and data type as shown below and name it "Tb_Login".

Column
Data Type
Id
Int (Primary Key. So set Is Identity=True
UserName
varchar(100)
Password
varchar(100)
               
  • Also create a Stored procedure to authenticate the login attempt.

CREATE PROCEDURE CheckLogin_sp
                @UserName  varchar(100),
                @Pwd       varchar(100)
AS
BEGIN
                SELECT UserName,[Password] from Tb_Login
                where UserName COLLATE Latin1_general_CS_AS=@UserName and [Password] COLLATE Latin1_general_CS_AS=@Pwd
END

Note: In this stored procedure i have also used the COLLATE Latin1_general_CS_AS to check for the exact username and password match because it is used to make the Sql queries case sensitive. e.g. if the username is admin and password is demo then if user enters Admin in username or Demo in password field then it will not match and it the log in attempt will get failed.
  • In the web.config file create the connection string to connect the asp.net website with the Sql server database as:

<connectionStrings>
    <add name="conStr" connectionString="Data Source=lalit;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>

NoteReplace the Data Source and Initial catalog (i.e. Database name) as per your application.

Asp.Net C# Code to implement remember me checkbox option in login form
  • In the code behind file (.aspx.cs) write the code as:.

First include the following required namespaces and write the code as:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
        SqlDataAdapter adp = new SqlDataAdapter();
        try
        {
            adp = new SqlDataAdapter("CheckLogin_sp", con);
            adp.SelectCommand.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim());
            adp.SelectCommand.Parameters.AddWithValue("@Pwd", txtPwd.Text.Trim());
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlDataReader dr = adp.SelectCommand.ExecuteReader();

            if (dr.HasRows)
            {
                if (chkRemember.Checked)
                {
                    dr.Read();
                    Response.Cookies["UserName"].Value = txtUserName.Text.Trim();
                    Response.Cookies["Pwd"].Value = txtPwd.Text.Trim();
                    Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30);
                    Response.Cookies["Pwd"].Expires = DateTime.Now.AddDays(30);       
                }
                else
                {
                    Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies["Pwd"].Expires = DateTime.Now.AddDays(-1);
                }
           ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Login Successful');"true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Invalid UserName or Password');"true);
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Error occurred : " + ex.Message.ToString() + "');"true);
        }
        finally
        {
            con.Close();
            adp.Dispose();
        }
    }

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {          
            if (Request.Cookies["UserName"] != null && Request.Cookies["Pwd"] != null)
            {
                txtUserName.Text = Request.Cookies["UserName"].Value;
                txtPwd.Attributes.Add("value", Request.Cookies["Pwd"].Value);
                chkRemember.Checked = true;
            }
        }
    }

Asp.Net VB Code to implement remember me checkbox option in login form
  • In the code behind file (.aspx.vb) write the code as:

First import the following required namespaces and write the code as:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

    Protected Sub btnLogin_Click(sender As Object, e As System.EventArgsHandles btnLogin.Click
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
        Dim adp As New SqlDataAdapter()
        Try
            adp = New SqlDataAdapter("CheckLogin_sp", con)
            adp.SelectCommand.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim())
            adp.SelectCommand.Parameters.AddWithValue("@Pwd", txtPwd.Text.Trim())
            adp.SelectCommand.CommandType = CommandType.StoredProcedure
            If con.State = ConnectionState.Closed Then
                con.Open()
            End If
            Dim dr As SqlDataReader = adp.SelectCommand.ExecuteReader()

            If dr.HasRows Then
                If chkRemember.Checked Then
                    dr.Read()
                    Response.Cookies("UserName").Value = txtUserName.Text.Trim()
                    Response.Cookies("Pwd").Value = txtPwd.Text.Trim()
                    Response.Cookies("UserName").Expires = DateTime.Now.AddDays(30)
                    Response.Cookies("Pwd").Expires = DateTime.Now.AddDays(30)
                Else
                    Response.Cookies("UserName").Expires = DateTime.Now.AddDays(-1)
                    Response.Cookies("Pwd").Expires = DateTime.Now.AddDays(-1)
                End If
                    ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Login Successful');"True)

            Else
                ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Invalid UserName or Password');"True)
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Error occurred : " & ex.Message.ToString() & "');"True)
        Finally
            con.Close()
            adp.Dispose()
        End Try
    End Sub
  
Protected Sub Page_Load(sender As Object, e As System.EventArgsHandles Me.Load
        If Not IsPostBack Then
            If Request.Cookies("UserName"IsNot Nothing AndAlso Request.Cookies("Pwd"IsNot Nothing Then
                txtUserName.Text = Request.Cookies("UserName").Value
                txtPwd.Attributes.Add("value", Request.Cookies("Pwd").Value)
                chkRemember.Checked = True
            End If
        End If

    End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

12 comments

Click here for comments
September 01, 2013 ×

Nice and very informative blog....
Rajesh

Reply
avatar
admin
September 01, 2013 ×

Thanks for your appreciation Rajesh Deepak..stay tuned and stay connected

Reply
avatar
admin
September 20, 2013 ×

I am getting error on line SqlDataReader dr = adp.SelectCommand.ExecuteReader(); that could not found the store procedure.

Any solution

Reply
avatar
admin
September 20, 2013 ×

Hello pratik..have you created the stored procedure "CheckLogin_sp" and connected your sql server database with the asp.net? Please check and notify me..

Reply
avatar
admin
December 02, 2013 ×

Hello sir, this blog is very useful, and thank you very much, but i still have some small doubt like which is the good practice for storing the user credentials like in cookies or database or in web.config file , please clearify me may be with a small practical example when to use to store data in cookies and database and in some other,..! Thank you.

Reply
avatar
admin
sanjay
March 16, 2014 ×

i love this blog

Reply
avatar
admin
March 17, 2014 ×

Thanks sanjay..i am glad you found this blog helpful..stay connected and keep reading..:)

Reply
avatar
admin
Anonymous
April 08, 2014 ×

Nice work...

Reply
avatar
admin
April 10, 2014 ×

Thanks for appreciating my work..it is always nice to hear that my article helped anyone in learning asp.net..stay connected and keep reading..:)

Reply
avatar
admin
April 12, 2014 ×

Hi,

Your code is good.
But if you see, browser by default ask for save password even you don't keep remember me checkbox.
My question is, if we save using browser save option it save into cookies but it saves plain value. How can I encrypt the same ?

Reply
avatar
admin
September 22, 2014 ×

thanks Shameem ahmad..

Reply
avatar
admin

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. Out Of Topic Show Conversion CodeHide Conversion Code Show EmoticonHide Emoticon

Thanks for your comment