How to Write a Simple login page in Asp.net

Ivinraj.S
Posted by Ivinraj.S under ASP.NET category on | Points: 40 | Views : 3153
Open Visual Studio and Create a New Website. Automatically you will have an empty page defined for you like this
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>

Go to Design View and you will notice there is nothing on your page. Now open your Toolbox and add a buttons and some textbox and depicted in the following.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblUsername" runat="server" Text="Username"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Button ID="btnlogin" runat="server" Text="Login" onclick="btnlogin_Click"
Width="47px" />
&nbsp;
<asp:Button ID="btnCancel" runat="server" Text="Cancel"
onclick="btnCancel_Click" />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>


Now as you can see our login page is created, Let us see how we can validate the login and what is needed to have a proper login. Open your Sql management Studio and Create a New Database, but if you already have it you will just follow the Step 2 where we add a table.

Step 1: Create a Database

Create Database FORUM

Step 2: Create a Table

CREATE TABLE [dbo].[Log_Users]
(
[Logid] [int] IDENTITY(100,1)PRIMARY KEY NOT NULL,
[Username] [varchar](55) NOT NULL,
[PASSWORD][varchar](55),
[Time_Logged_in] [datetime] NOT NULL,
[Time_Logged_Out] [datetime] NOT NULL,
[Status] [int] NOT NULL,
[Date_Logged_in] [datetime] NOT NULL,
[E_MAIL] [varchar](55) NOT NULL
)

Step 3: Let us Add Sample Data

insert into dbo.Log_Users
values('Vuyiswamb','wowididit',GETDATE(),'02/07/2010',1,GETDATE(),'Vuyiswa@wow.com')
insert into dbo.Log_Users
values('SheoNarayan','Oops?',GETDATE(),'02/09/2010',1,GETDATE(),'Sheo@wowMail.com')
Now that we have our sample Data. Please note that you can use any other field but the username and Password fields are the most important. Now let us create our stored Procedure.
Step 4: Create a Stored Prcedure that will validate and return a valid Integer.
Create Proc [dbo].[prcLoginv]
(
@Username VarChar(50),
@UPassword varChar(50),
@OutRes int OUTPUT
)
AS
set @OutRes = (SELECT count(*) FROM [dbo].Log_Users
WHERE Username = @Username And [Password] = @UPassword)
if(@OutRes = 1)

begin
set @OutRes = 1--Login is Correct
end
else
begin
set @OutRes = 0 --Bad login
end
In the above Stored Procedure we count the Records that have matched the Records and if there is one record found then it is a good login else it is a bad login. But how will you use this in your asp.net Page. First we have to create a Function that will access the stored procedure and call that function in click event of the button. Create a Function as show below in your page not inside your page load because you will get an Error.
public int Validate_Login(String Username, String Password)
{
SqlConnection con = new SqlConnection(@"User id=sa;Password=ivin;Server=ivin/pc;Database=Forum");
SqlCommand cmdselect = new SqlCommand();
cmdselect.CommandType = CommandType.StoredProcedure;
cmdselect.CommandText = "[dbo].[prcLoginv]";
cmdselect.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = Username;
cmdselect.Parameters.Add("@UPassword", SqlDbType.VarChar, 50).Value = Password;
cmdselect.Parameters.Add("@OutRes", SqlDbType.Int, 4);
cmdselect.Parameters["@OutRes"].Direction = ParameterDirection.Output;
cmdselect.Connection = con;
int Results = 0;
try
{
con.Open();
cmdselect.ExecuteNonQuery();
Results = (int)cmdselect.Parameters["@OutRes"].Value;
}
catch (SqlException ex)
{
lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
return Results;
}
As you can see this Function return an Integer, as we said before this will return either a 1 which is equal to “Good” and other numbers will be “Bad”. The login Data should be clean, no Duplicates should be there because this will break your functionality. It might return the duplicates and the count might not match the if statement that you will see later in this article. Double click you Button and add the following code in the Click event of the Button.
protected void btnlogin_Click(object sender, EventArgs e)
{


int Results = 0;

if (txtUsername.Text != string.empty && txtPassword.Text != string.empty)

{

Results = Validate_Login(txtUsername.Text.trim(), txtPassword.Text.trim());

if (Results == 1)

{

lblMessage.Text = "Login is Good, Send the User to another page or enable controls";

}

else

{

lblMessage.Text = "Invalid Login";

lblMessage.ForeColor = System.Drawing.Color.Red;

//Dont Give too much information this might tell a hacker what is wrong in the login

}

}

else

{

lblMessage.Text = "Please make sure that the username and the password is Correct";

}

}

Comments or Responses

Login to post response