Monday, March 7, 2011

Restricting User To Login Multiple Times Using Same Credentials

Generally in many websites after you get logged in you will be redirected to home page. While this page is running if the user selects the new window and open the Login page again and if he provides the same credentials which was provided earlier then he will be automatically redirected to home page. But in this article I am going to explain how to restrict this if you consider the examples of gmail.com or yahoo.com once in a particular user is logged in they won’t restrict the user but here I will provide that feature and check whether if a particular user is logged in I will display it as already logged in.

Introduction

Generally in many websites after you get logged in you will be redirected to home page. While this page is running if the user selects the new window and open the Login page again and if he provides the same credentials which was provided earlier then he will be automatically redirected to home page. But in this article I am going to explain how to restrict this if you consider the examples of gmail.com or yahoo.com once in a particular user is logged in they won’t restrict the user but here I will provide that feature and check whether if a particular user is logged in I will display it as already logged in.


Concepts Covered In This Article:

1)    Basics of handling Cache Memory
2)    Maintaining SQL Session State
3)    Database Retrieval
4)    Maintaining Session ID Uniquely for each user
In my example I will have 2 pages namely

Login.aspx

Home.aspx

Procedure:

a)     Open Visual Studio(I will use VS2010) and select new project and name it as State Server.
b)    Select a web application from the templates available.
c)     Now name it Default.aspx as Login.aspx
d)    Name About.aspx as Home.aspx.
e)   Follow the steps which I explain now.
This procedure can be explained step by step using this way:

Step 1:

Now after adding the pages first we will consider the Login.aspx page in that First and foremost thing is create a class studentInfo of Serializable type to return the values of username and password.
[Serializable]
public class StudentInfo
{//Default Constructor
public StudentInfo()
{
}
/// <summary>
/// Create object of student Class
/// </summary>
/// <param name="intRoll">Int RollNumber</param>
/// <param name="strName">String Name</param>
public StudentInfo(string UserName, string Password)
{
this.UName = UserName;
this.Pass = Password;
}
private string UserName;
private string Password;
public string UName
{
get
{return UserName;
}
set
{UserName = value;
}
}
public string Pass
{
get
{return Password;
}
set
{Password = value;
}
}
}
Step 2:

Now connect to the database by giving the valid connection string this is to be given in the button on click event. That is done in this way ,
StudentInfo _objStudentInfo=new StudentInfo(UserName.Text,Password.Text);
Session["objStudentInfo"] = _objStudentInfo;
SqlConnection con;
con = new SqlConnection("server=user-182;user id=sa;password=007;database=srikanthch");
con.Open();
SqlCommand cmd;
SqlDataReader rdr;
cmd = new SqlCommand("select UserName,Password from Sessions", con);
rdr = cmd.ExecuteReader();
Step 3:

Now that we have the records in the rdr object now we have to check whether the particular user is a valid user or not and we have assign some cache memory to make the user to be accessed only once. We insert the key value into the cache where the key consists of the username and password that can be done in this way.
while (rdr.Read())
{
if (rdr["UserName"].ToString() == UserName.Text && rdr["Password"].ToString() == Password.Text)
{
string sKey = UserName.Text + Password.Text;
string sUser = Convert.ToString(Cache[sKey]);
if (sUser == null || sUser == String.Empty)
{
// No Cache item, so sesion is either expired or user is new sign-on
// Set the cache item and Session hit-test for this user---
TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut,
System.Web.Caching.CacheItemPriority.NotRemovable, null);
Session["user"] = UserName.Text + Password.Text;
// Let them in - redirect to main page, etc.
Response.Redirect("Home.aspx");
}
else
{// cache item exists, so too bad... 
lblDisplay.Text = "<Marquee><h1><font color=red>Already Logged IN</font></h1></marquee>";
return;
}
}
else
{lblDisplay.Text = "Invalid UserName and Password Try Again !!!";
}
}
Now if a particular user is valid he will be redirected to the home page else we will return an error message stating that Credentials are invalid.

This is all what we have in Login.aspx. Now let’s move to Home.aspx page.
Step 4:

In this we will use the Session variable User Name and we will set that name to a label in this way.
StudentInfo _objStudentInfo = (StudentInfo)Session["objStudentInfo"];
lblDisplayUserName.Text = _objStudentInfo.UName;
Step 5:

Finally we need to remove the Session and redirect it to the Login page when a User clicks on Logout button.
Session.Abandon();Response.Redirect("Login.aspx");


Actually with this we are done but we need to understand how to set Session ID using SQL Session State.

For this in web.config file we need to place a tag called <SessionState>

This tag should be entitled in between

<system.web><sessionState mode="SQLServer" sqlConnectionString="data source=user-182;user id=sa;password=007" cookieless="false" timeout="20"></sessionState>
</system.web>

After this the SQL Server Session Mode configuration is done using aspnet_regsql Command.

Go to the Command prompt and go the directory where the framework version is there and type this

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regsql -S user-182 -U sa –P 007 -ssadd -sstype p
So now u will have a database created with name ASP State and there will be 2 inbuilt tables too. They are :

ASPStateTempApplications

ASPStateTempSessions.
That table structure can be seen in this way:


Above pic shows the ASPState database and the tables in that the session data is stored in the table ASPStateTempSessions.

Now we are done with entire coding part now we will see how the screen shots will go on..

Screen Shots:

Picture - 1

This is the first page in our sample which is Login.aspx

 

Picture - 2
Now the user must provide his credentials that is the User Name and Password and must click Login button.

Picture - 3 

After the Successful login the User would be redirected to the main Home.aspx.


Picture  - 4 

Now if the particular user tries to open another browser and provide same credentials then it will display as the user is already Logged in.


Conclusion :


So in this article I gave a basic idea how to capture a Sql Session State and assigning unique session id for each User who had logged in and string it in a Cache memory. This requirement may look strange but I tried a different way . Hope it would help for some one who thinks differently like me.


Download


 Download source code for Restricting User To Login Multiple Times Using Same Credentials




No comments:

Post a Comment