ASP.NET Password Protected Login using the Session Object

Although ASP.NET offers forms authentication for creating a password protected login system you can still use the Session Object to create a simple admin login system.

First of all we will create a 'login.aspx' file that displays a textbox control for the username and password. When the asp button 'LoginButton' is clicked the click event is raised and the event handler 'Login' is called.

This subroutine checks the text property of the Username and Password textbox controls to see if they match 'admin' and 'admin' respectively. If they do then a session Session("Admin") is created and set to True and the user is redirected to the 'default.aspx' page. If not then the Session is set to False and the Literal control 'LtlLogin' text property is set to display a login error.

Create a file Login.aspx

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Public Sub Login(ByVal s As Object, ByVal e As EventArgs)

If UserName.Text = "admin" And Password.Text = "admin" Then
   Session("Admin") = True
   Response.Redirect("default.aspx")
 Else
   Session("Admin") = False
   LtlLogin.Text = "<p>Sorry you have provided incorrect login details.</p>"
End If
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Admin Log In</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Admin Log In</h1>

Username:<br />
<asp:TextBox ID="UserName" RunAt="server" /><br />
Password:<br />
<asp:TextBox ID="Password" TextMode="password" Runat="server" /><br />
<asp:Button ID="LoginButton" Text="Log In" OnClick="LogIn" Runat="server" /><br />

<asp:Literal ID="LtlLogin" Runat="server" />

</div>
</form>
</body>
</html>

To protect a file you can simply place code within the Page Load event that will check whether the session Session("Admin") is true or false. If it's false then redirect the user back to the login.aspx file.

Default.aspx

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
  If Session("Admin") <> True Then
    Response.Redirect("login.aspx")
  End If
End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Admin Area</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Welcome to the Admin Area.</p>
</div>
</form>
</body>
</html>

Learn how to create an ASP.NET login with Forms Authentication.

Get the best asp web hosting provider now and save 30%

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Free ASP Hosting