cookieChoices = {};

Friday, 20 September 2013

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. 

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.

C#.Net 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;
            }
        }
    }

VB.Net 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

No comments:

Post a Comment