Saturday, October 22, 2011

User validation authentication using session in ASP.NET


For Forms Authentication, read this Forms Authentication with C# and managing folder lavel access with multiple web.config files in ASP.NET


In this example i m showing how to validate a user across different pages whether user is logged in or not using session variables in Global.asax through Session_Start event and Application_OnPostRequestHandlerExecute event which checks for the login validation which occurs when ant asp.net event handler finish execution
Here is my login page , i've used hard coded values to login

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Login.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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:left" >
<table width="40%" style="text-align: center">
<tr><td style="width: 20%">
<asp:Label ID="lblUserName"
runat="server" Text="Enter UserName:">
</asp:Label></td>
<td style="width: 20%">
<asp:TextBox ID="txtUserName"
runat="server">
</asp:TextBox></td>
</tr>
<tr>
<td style="width: 20%">
<asp:Label ID="lblPassword" runat="server"
Text="Enter Password:">
</asp:Label></td>
<td style="width: 20%" >
<asp:TextBox ID="txtPassword" runat="server"
TextMode="Password">
</asp:TextBox></td>
</tr><tr><td colspan="2" align="right">
<asp:Button ID="btnLogin" runat="server"
Text="Sign in" OnClick="btnLogin_Click" />
</td></tr>
</table>
<asp:Label ID="Label1" runat="server"
Text="Label">
</asp:Label><br />
</div>


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

After checking the username and password i m creating a new Session variable and setting the flag kindaa value in it , which is "Yes" in this example, this session value will be checked when ever user go to other pages and if it's null than user in not logged in
protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "amit" && txtPassword.Text == "amit")
{
Session["Authenticate"] = "Yes";
Response.Redirect("Default2.aspx");
}
else
Label1.Text = " login failed";
}

In Global.asax, in Session_Start event i m assigning null value to the session variable created at the time of Login and than calling the method to check the login, same is in Application_OnPostRequestHandlerExecute event as well 
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["Authenticate"] = "";
CheckLogin();

}
void Application_OnPostRequestHandlerExecute()
{
CheckLogin();
}

void CheckLogin()
{
string Url = Request.RawUrl;
int count = Url.Length - 10 ;
string TestUrl = Url.Substring(count);
string SessionData = Session["Authenticate"].ToString();
if (SessionData == "" && TestUrl != "Login.aspx")
{
Response.Redirect("~/Login.aspx");
}
}


Download the sample code attached