Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to create a Login page in ASP.NET

Author: Alanna Kremer
Download Source Code : 1408_LoginPage.zip

We will see in this article that how we can create a Login page in ASP.NET.

 

I have written an article on DevASP.NET about how to create a signup or register page in ASP.NET. When you have created a register page then you need to create login page as well. I will create a simple login page using the same database which I have used for signup page. This SQL Server database (SampleApplicationDatabase) has a table (Account). Table (Account) has six columns (AccountID, FirstName, LastName, Email, Password, ConfirmPassword and CreateDate). I will use Email and Password fields for login purposes and I will check both values from database when user will try to login. For this purpose I have written a stored procedure to check valid user. Of course, I have also implemented client side validation by using RequiredFieldValidator controls and RegularExpressionValidator for Email.
 
Let’s see how we can create a login page. You can download source code.
  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual C# or Visual Basic > ASP.NET Empty Web Site > Click Ok
  4. Website > Add New Item > Web Form > Click Add (Default.aspx)
  5. Website > Add New Item > Web Form > Click Add (Rename as Register.aspx)
  6. Website > Add New Item > Web Form > Click Add (Rename as UserPage.aspx
  7. Add code below in Default.aspx

    <table>
        <tr>
            <td colspan="3" style="height: 21px; text-align: center">
                <span style="font-size: 16pt">Please login if you have account</span></td>
        </tr>
        <tr>
            <td colspan="3" style="height: 21px; text-align: center">
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: center; height: 21px;">
                <span style="font-size: 24pt">
                Login</span>
            </td>
        </tr>
        <tr>
            <td style="width: 71px" valign="top">
                    <asp:Label ID="lblEmail" runat="server" Text="Email:"></asp:Label></td>
            <td style="width: 178px; text-align: right;" valign="top">
                <asp:TextBox ID="txtEmail" runat="server" ></asp:TextBox></td>
            <td style="width: 37px" valign="top">
                <asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ControlToValidate="txtEmail"
                    Display="Dynamic" ErrorMessage="Email Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server"
                    ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="Provide Valid Email Address"
                    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator></td>
        </tr>
        <tr>
            <td style="width: 71px; height: 26px;">
                <asp:Label ID="lblPassword" runat="server" Text="Password:"></asp:Label></td>
            <td style="width: 178px; height: 26px; text-align: right;">
                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox></td><
            <td style="width: 37px; height: 26px">
                <asp:RequiredFieldValidator ID="PasswordRequiredFieldValidator" runat="server" ControlToValidate="txtPassword"
                   Display="Dynamic" ErrorMessage="Password Required">*</asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: right">
            </td>
            <td colspan="1" style="width: 37px; text-align: right">
            </td>
        </tr>
        <tr>
            <td style="width: 71px; height: 27px;">        </td>
            <td style="width: 178px; text-align: right; height: 27px;">
                <asp:Button ID="btnLogin" runat="server" Style="position: relative"
                    Text="Login" onclick="btnLogin_Click" /></td>
            <td style="width: 37px; height: 27px; text-align: right">
            </td>
        </tr>
        <tr>
            <td style="width: 71px; text-align: right; height: 27px;">
            </td>
            <td style="width: 178px; text-align: right; height: 27px;">
                <asp:Label ID="lblNewUser" runat="server" Text="New User?"></asp:Label>
                <asp:HyperLink ID="RegisterHyperLink" runat="server" Font-Bold="False" Font-Names="Georgia"
                    NavigateUrl="~/Register.aspx" Style="position: relative">Register</asp:HyperLink>&nbsp;
            </td>
            <td style="width: 37px; height: 27px; text-align: right">
            </td>
        </tr>
        <tr>
            <td colspan="3" style="height: 27px; text-align: center">
                <asp:ValidationSummary ID="LoginValidationSummary" runat="server" />
            </td>
        </tr>
    </table>
    <br />
    <asp:Label ID="lblMessage" runat="server"></asp:Label>

    I have used RequiredFieldValidator for both email and password and I have also used a RegularExpressionValidator for email. I have displayed a HyperLink control to direct the user to register or Signup page.
     
  8. Write below stored procedure in SQL Server database to verify user.

    CREATE PROCEDURE dbo.VerifyAccount
           @Email Varchar(100),
           @Password NVarchar(50),
           @Verify BIT OUTPUT
          
           AS
          
           BEGIN
          
           DECLARE @RecordCount INT
          
           SELECT @RecordCount = Count(*) FROM Account WHERE Email = @Email AND Password = @Password
          
           IF @RecordCount = 1
           BEGIN
                  SET @Verify = 1
           END
           ELSE
           BEGIN
                  SET @Verify = 0
           END
          
           END
     
    dbo.VerifyAccount stored procedure checks in Account table for any account against email and password.
     
  9. Open code behind file and include following namespace.

    C#
     
    using System.Data;
    using System.Data.SqlClient;
     
    VB.NET
     
    Imports System.Data
    Imports System.Data.SqlClient
     
  10. Write two functions in code behind file to verify user and to get user name.

    Function to verify user
     
    C#
     
    public bool VerifyAccount(string email, string password)
    {
        bool result;
     
        string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connstring);
     
        SqlCommand cmd = new SqlCommand("VerifyAccount", conn);
        cmd.CommandType = CommandType.StoredProcedure;
     
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;
        cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50).Value = password;
     
        SqlParameter pVerify = new SqlParameter("@Verify", SqlDbType.Bit);
        pVerify.Direction = ParameterDirection.InputOutput;
        pVerify.Value = DBNull.Value;
     
        cmd.Parameters.Add(pVerify);
     
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
     
            if ((bool)pVerify.Value == true)
            {
                result = true;
            }
            else
            {
                result = false;
            }
        }
        catch (Exception ex)
        {
            result = false;
        }
        conn.Close();
     
        return result;
    }
     
    VB.NET
     
    Public Function VerifyAccount(email As String, password As String) As Boolean
        Dim result As Boolean
     
        Dim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"
        Dim conn As New SqlConnection(connstring)
     
        Dim cmd As New SqlCommand("VerifyAccount", conn)
        cmd.CommandType = CommandType.StoredProcedure
     
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email
        cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50).Value = password
     
        Dim pVerify As New SqlParameter("@Verify", SqlDbType.Bit)
        pVerify.Direction = ParameterDirection.InputOutput
        pVerify.Value = DBNull.Value
     
        cmd.Parameters.Add(pVerify)
     
        Try
            conn.Open()
            cmd.ExecuteNonQuery()
     
            If CBool(pVerify.Value) = True Then
                result = True
            Else
                result = False
            End If
        Catch ex As Exception
            result = False
        End Try
        conn.Close()
     
        Return result
    End Function
     
    Function to get user name
     
    C#

    public string GetUser(string email)
    {
        string userName = "";
     
        string sqlQuery = "SELECT (FirstName + ' ' + LastName) AS UserName FROM Account WHERE Email = @Email";
        string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connstring);
     
        SqlCommand cmd = new SqlCommand(sqlQuery, conn);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;
     
        try
        {
            conn.Open();
            userName = cmd.ExecuteScalar().ToString();
        }
        catch (Exception ex)
        {
     
        }
        finally
        {
            conn.Close();
        }
     
        return userName;
    }
     
     
    VB.NET
     
    Public Function GetUser(email As String) As String
        Dim userName As String = ""
     
        Dim sqlQuery As String = "SELECT (FirstName + ' ' + LastName) AS UserName FROM Account WHERE Email = @Email"
        Dim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"
        Dim conn As New SqlConnection(connstring)
     
        Dim cmd As New SqlCommand(sqlQuery, conn)
        cmd.CommandType = CommandType.Text
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email
     
        Try
            conn.Open()
            userName = cmd.ExecuteScalar().ToString()
     
        Catch ex As Exception
        Finally
            conn.Close()
        End Try
     
        Return userName
    End Function
     
    VerfiyAccount() function verifies that an account exists using stored procedure against entered email and password.
     
    GetUser() function retrieves full name of the user against email. For this, you have to make sure that there will be only one user for one email address. Note in SQL query, I have concatenated first and last name to get as single string.
     
  11. Write code below in login button click event

    C#
     
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        bool result = VerifyAccount(txtEmail.Text, txtPassword.Text);
     
        if (result == true)
        {
            Session["ValidUser"] = true;
            Session["UserName"] = GetUser(txtEmail.Text);
     
            Response.Redirect("UserPage.aspx");
        }
        else
        {
            Session["ValidUser"] = false;
            lblMessage.Text = "Sorry you cannot login, please provide correct Email and password";
        }
    }
     
    VB.NET
     
    Protected Sub btnLogin_Click(sender As Object, e As EventArgs)
        Dim result As Boolean = VerifyAccount(txtEmail.Text, txtPassword.Text)
     
        If result = True Then
            Session("ValidUser") = True
            Session("UserName") = GetUser(txtEmail.Text)
     
            Response.Redirect("UserPage.aspx")
        Else
            Session("ValidUser") = False
            lblMessage.Text = "Sorry you cannot login, please provide correct Email and password"
        End If
    End Sub
     
    In Login button click event, first I have called the VerifyAccount() function. If it is true then I have set session true for that user. I have also called GetUser() method and stored string value in a session object. Then I have redirected the user to UserPage.aspx page.
     
  12. Add code below in UserPage.aspx

    <asp:Label ID="lblWelcome" runat="server"></asp:Label>
    <br />
    <br />
    <asp:Button ID="btnLogout" runat="server" Text="Logout"
        onclick="btnLogout_Click" />

  13. Write code below in code behind file

    C#
     
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if ((bool)Session["ValidUser"] == true)
            {
                string userName = Session["UserName"].ToString();
                lblWelcome.Text = "Hello " + userName + ", Welcome to our website.";
                btnLogout.Visible = true;
            }
            else
            {
                lblWelcome.Text = "Sorry you cannot visit this page. Please Login to visit this page.";
                btnLogout.Visible = false;
            }
        }
    }
    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Session["ValidUser"] = false;
        Response.Redirect("Default.aspx");
    }
     
     
    VB.NET
     
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If CBool(Session("ValidUser")) = True Then
                Dim userName As String = Session("UserName").ToString()
                lblWelcome.Text = "Hello " + userName + ", Welcome to our website."
                btnLogout.Visible = True
            Else
                lblWelcome.Text = "Sorry you cannot visit this page. Please Login to visit this page."
                btnLogout.Visible = False
            End If
        End If
    End Sub
     
    Protected Sub btnLogout_Click(sender As Object, e As System.EventArgs) Handles btnLogout.Click
        Session("ValidUser") = False
        Response.Redirect("Default.aspx")
    End Sub
     
    In Page Load event of the user page, I have checked session. If user session is true then I have retrieved user name from other session object and displayed a welcome message for that user.
     
  14. Set Default.aspx as start page and Press F5. Enter values in database table directly or using Signup page. Enter email and password and click Login.

 

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to bind data to GridView using JQuery and WebMethod in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net