ASP.NET Login form Example validating user from SQL Server Database

ASP.NET Login form Example validating user from SQL Server Database

Designing a Login form is not so easy as we are thinking. Modern login pages comes with various rich feature such as Validating User, Form Validation, Capcha or Remember Password. In this demo app we are going to show you how to authenticate an user using records from SQL Server user table. To start with first you required to Create a user table in SQL Server.

Create a Table for Users

To Create an user table which will store Login details such as UserID or Password your required to run the following Transact-SQL Query.

CREATE TABLE user_table (
id INT PRIMARY KEY, 
userid VARCHAR(255) NOT NULL, 
password VARCHAR(56)
);

Then insert some sample records.

In front-end Copy n Paste my default.aspx page Codes. Here I have 2 textbox Controls such as user id and password. To stop spam here I am using required field validation for both the fields. Additionally to valid an email id I am using ASP.NET RegularExpressionValidator validation control. Then in my form I have a submit button. Which submits the form to server using post method.

Default.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>ASP.NET Login form Example</title>
<link rel="stylesheet" href="master.css" />
</head>
<body>
<form id="frmLogin" runat="server">
<div class="loginDiv rounded">
<div class="formControl">
Email ID&nbsp;<span style="color: Red;">*</span>
</div>
<div class="formControl">
<asp:TextBox ID="txtEmailID" runat="server" Width="100%"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmailID" runat="server" ControlToValidate="txtEmailID"
Display="Dynamic" ErrorMessage="Email should not be blank.<br />"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmailID" runat="server"
ControlToValidate="txtEmailID" Display="Dynamic" ErrorMessage="Enter a valid Email ID.<br />"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</div>
<div class="formControl">
Password&nbsp;<span style="color: Red;">*</span>
</div>
<div class="formControl">
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="100%"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" runat="server" ControlToValidate="txtPassword"
Display="Dynamic" ErrorMessage="Password should not be blank."></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnVisitorLogin" runat="server" Text="Login" />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<input type="checkbox" value="remember-me" />&nbsp;Remember me<a href="#" class="pull-right margin-gap">Need help?</a>
</div>
</form> 
</body>
</html>

To valid user from SQL Server in Code behind file I am executing my business logics inside “btnVisitorLogin_Click” event. To connect and execute SQL query which will fetch data I imported the system files “System.Data” and “System.Data.SqlClient” in page header.

To establish a Connection I am creating a new instance for SQL Server Connection object. Which accepts connection string from my web.config file. Look at the below code to know how to declare connection string in web.config file.

<connectionStrings>
<add name="connStr" connectionString="Data Source=WINSERV;Initial Catalog=phase2;User ID=sa;Password=win#serv" providerName="System.Data.SqlClient"/>
</connectionStrings>

Here Data Source is my Database Server name. Initial Catalog is the Database name and User id, password is for the database user.

To compare user Credentials with database records here I am executing a command object and fetching user table records to a SQL DataReader. As you know datareader works like a pointer. Using a DataReader compare to a DataSet we can minimize the login time. To validate a user I am running a while loop until the end record of SQL DataReader “dr_pass”. For each record inside the while loop I am comparing the value with user password. In case it returns true I am allowing the user to redirect into the application dashboard page.

Default.aspx.vb

Imports System.Data
Imports System.Data.SqlClient

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub btnVisitorLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnVisitorLogin.Click

Dim oMyConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString)
Dim oMyCommand As New SqlCommand("SELECT password, userid FROM user_table WHERE userid= '" & txtEmailID.Text & "' ", oMyConnection)
Dim dr_pass As SqlDataReader

oMyConnection.Open()
dr_pass = oMyCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)

If Not dr_pass.HasRows Then
lblMessage.Text = "Invalid Email or Password."
End If

While dr_pass.Read
If Trim(txtPassword.Text) = dr_pass("password") Then
Session.Add("sess_uid", dr_pass("userid"))
Response.Redirect("../Dashboard.aspx")
End If
End While
End Sub
End Class

master.css

#frmLogin { max-width: 300px; margin: 0 auto; padding-top: 120px; }
.formControl { font-family: Verdana; font-size: 12px; }
.loginDiv { width:300px; margin-top: 20px; padding: 20px 20px 20px 20px; background-color: #f7f7f7; -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); } 
.rounded { border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }

The above demo will run without CSS. But beauty attracts eyes. This is the cause I am with the above CSS classes. Apply this CSS to have a basic look. You modify it as per the mock-up.

Source of Image: http://www.grfxpro.com