HI WELCOME TO KANSIRIS

HOW TO CREATE LOGIN FORM/PAGE AND IMPLEMENT REMEMBER ME NEXT TIME CHECKBOX IN ASP.NET

Leave a Comment
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.



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;
            }
        }
    }

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.