Session Management Techniques
Before we proceed, let us see what all session management
techniques are present in the ASP.NET framework.
· 1. In-Proc.
· 2. SQLServer.
· 3. StateServer.
How to
configure Sessions
To configure the session management we need to specify the
settings in the
web.config file. Typical settings inweb.config looks like:<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>
Let us see what each of these attributes mean.
|
mode
|
This specifies the type of session
management we want to use. it could be
InProc,SQLServer, and StateServer |
|
stateConnectionString
|
If we use
StateServer as session management technique then this specifies the
location of the server that is handling the session data. |
|
sqlConnectionString
|
If we use
SQLServer as session management technique then this specifies the
database
connectionstring that will store the session data. |
|
cookieless
|
This specifies whether we will be
using
cookies to identify sessions or we want session info appended in URL.
It could be true or false. |
|
timeout
|
This specifies the time for which the
session should be active. after this much time of inactivity the session will
expire.
|
NOW lets see how can we apply these techniques in additional with other security measures .
I have created a login page and a welcome page that is redirected when correctly loggedin...............
THE DESIGN PAGE:
<%@ Page Language="C#"
AutoEventWireup="true"
CodeFile="sessionmanagement.aspx.cs"
Inherits="sessionmanagement"
%>
<!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>Login Form with session Stored in InProc</title>
</head>
<body>
<form id="form1"
runat="server">
<center><div>
<table>
<tr>
<td>
Username:
</td>
<td>
<asp:TextBox ID="txtUserName"
runat="server"/>
<asp:RequiredFieldValidator ID="rfvUser"
ErrorMessage="Please
enter Username" ControlToValidate="txtUserName" runat="server" />
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="txtPWD"
runat="server"
TextMode="Password"/>
<asp:RequiredFieldValidator ID="rfvPWD"
runat="server"
ControlToValidate="txtPWD"
ErrorMessage="Please
enter Password"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit"
runat="server"
Text="Submit"
onclick="btnSubmit_Click"
/>
<asp:Label ID="warninglbl" runat="server" Text="" Visible="false"></asp:Label>
</td>
</tr>
</table>
</div>
</center>
</form>
</body>
</html>
THE CODE BEHIND PAGE:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial
class sessionmanagement
: System.Web.UI.Page
{
string
sqlconn = ConfigurationManager.ConnectionStrings["sqlTestconn"].ConnectionString.ToString();
public static int
countclicked = 0;
protected void Page_Load(object
sender, EventArgs e)
{
this.SmartNavigation
= true;
if
(!IsPostBack)
{
try
{
warninglbl.Visible = false;
string
ComputerName = Request.ServerVariables["REMOTE_HOST"];
string
IPAddress = Request.ServerVariables["REMOTE_ADDR"];
string
Browser = Request.ServerVariables["HTTP_USER_AGENT"];
}
catch
(Exception ex)
{
Response.Write(ex.Message);
}
}
if
(countclicked > 3)
{
Session["isbanned"] = true;
}
else
{
Session["isbanned"] = false;
}
}
private void Login()
{
string
username = txtUserName.Text;
string
password = txtPWD.Text;
SqlConnection
conn = null;
try
{
btnSubmit.Enabled = false;
conn = new
SqlConnection(sqlconn);
if
(conn.State == ConnectionState.Closed)
{
conn.Open();
}
//
SqlCommand cmd = new SqlCommand();
string
sqlstr = "select * from login where
username='" + username + "' and
password='" + password + "';
";
SqlDataAdapter
da = new SqlDataAdapter(sqlstr,
conn);
DataTable
dt = new DataTable();
da.Fill(dt);
if
(dt.Rows.Count > 0)
{
string
dbname = dt.Rows[0]["username"].ToString();
string
dbpass = dt.Rows[0]["password"].ToString();
if
(dbname == username && dbpass == password)
{
Session["username"] = username;
Session["islogged"] = true;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
"loginmsg", "alert('CONGRASS... YOU HAVE BEEN REDIRECTED TO USER
PAGE!!!')", true);
Response.Redirect("WelcomePage.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
"loginmsg", "<script>alert('WRONG USERNAME OR
PASSWORD!!')</script>", true);
Session["islogged"] = false;
}
}
else
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
"errmsg", "alert('WRONG
USERNAME OR PASSWORD!!PLEASE TRY AGAIN')", true);
}
}
catch
(System.Threading.ThreadAbortException
lException)
{
// do
nothing
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
btnSubmit.Enabled = true;
conn.Close();
conn = null;
}
}
protected void btnSubmit_Click(object
sender, EventArgs e)
{
if (!(Boolean)Session["isbanned"])
{
Login();
}
else {
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
"errmsg", "alert('YOU
HAVE TRIED MORE THEN 3 TIMES!!!! YOUR ACCOUNT HAS BEEN LOCKED FOR TODAY PLEASE
CONTANCT THE ADMIN>>')", true);
}
countclicked++;
if (countclicked
> 3)
{
Session["isbanned"]
= true;
btnSubmit.Enabled = false;
warninglbl.Visible = true;
warninglbl.Text= "YOU HAVE TRIED MORE THEN 3 TIMES!!!! YOUR ACCOUNT
HAS BEEN LOCKED FOR TODAY PLEASE CONTACT THE ADMIN>>>>>'";
}
}
}
THE WELCOME PAGE:
THE CODE BEHIND PAGE:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial
class session_management_WelcomePage
: System.Web.UI.Page
{
string
sqlconn = ConfigurationManager.ConnectionStrings["sqlTestconn"].ConnectionString.ToString();
protected void Page_Load(object
sender, EventArgs e)
{
this.SmartNavigation
= true;
if
(!IsPostBack)
{
try
{
if
(!(Boolean)Session["islogged"])
{
Response.Redirect("sessionmanagement.aspx");
}
else
{
string
username = Session["username"].ToString();
Label1.Text = "WELCOME MR. " + username+" -you have successfully loged in!!!!!!!!!"
;
}
}
catch
(Exception ex)
{
Response.Write(ex.Message);
Response.Redirect("sessionmanagement.aspx");
}
}
}
protected void lgtbtn_Click(object
sender, EventArgs e)
{
Session["islogged"]
= false;
Session["username"]
= "";
Response.Redirect("sessionmanagement.aspx");
}
}
/////////////////////////////////////////////////////////////////////////
here we are using the session variables to store the user data.now to store these session we can use three ways as prescribed above in following ways........
IN WEBCONFIG FILE:
FOR InProc:
<sessionState mode="InProc" allowCustomSqlDatabase="true" sqlConnectionString="Data Source=backupserver\test;Initial Catalog=ASPState;User
ID=******;Password=******" cookieless="false" timeout="100"/>
FOR SQLSERVER:
<sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="Data Source=backupserver\test;Initial Catalog=ASPState;User
ID=sa;Password=sa" cookieless="false" timeout="100"/>
FOR STATESERVER:
<sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" cookieless="false" timeout="100"/>
NOW I have given example(above code) for InPROC storege ….now lets see hoe we can
store the session variables data in SQLSERVER.
USE THE ABOVE MENTIONED CONFIG IN YOUR WEBCONFIG
FILE………i.e for SQLSERTVER
AND THE REST OF THE CONCEPT IS SAME…i.e for programming .
But before you need to install the aspstate database in your
sqlserver.
STEPs FOR INSTALLING THE DB:
1.Running both ASP.NET and classic ASP in the same application pool?
If the application pool is
also running classic ASP pages, and those classic ASP pages use .NET 2.0
components, and those classic ASP pages which use .NET components are called before any ASP.NET 1.1 page, then we'll load CLR 2.0 (first come, first serve
) and of course it will look for his specific
ASPState version.
Ok, there are a lot of "if" in this
case, but it's still a possibility... not my scenario, through.
2.Where are your session tables?
If you use aspnet_regsql wizard, session tables are not added by default so you need to run the following command:
THE PATH WHERE YOU WILL GET
THE EXE iS:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319
THE WIZARD ONLY
INSTALLs the asp membership tables etc…
aspnet_regsql.exe
-S <servername> -E -ssadd
-sstype p
YOUR DB IS INSTALLED…………..
Are you sure you can run it?
Of course we still need
permissions to access the database... so make sure the account used in your
connection string can connect to the database has EXEC permission on the following
stored procedures in ASPState database:
- TempGetAppID
- TempGetStateItem
- TempGetStateItemExclusive
- TempReleaseStateItemExclusive
- TempInsertStateItemLong
- TempInsertStateItemShort
- TempUpdateStateItemLong
- TempUpdateStateItemShort
- TempUpdateStateItemShortNullLong
- TempUpdateStateItemLongNullShort
- TempRemoveStateItem
- TempResetTimeout
Well... to make things easier
in my sample, I just granted NETWORK SERVICE dbo permission on ASPState and I got my repro up an running.
No comments :
Post a Comment