User Validation Authentication Using Session In ASP.NET

This post explains how to use User Validation Authentication Using Session In ASP.NET to validate users, Consider a scenario where you don't want to use membership class or Form Authentication techniques provided by .NET 2.0, in those situation this example might be helpful

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 an asp.net event handler finish execution

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

Here is my login page, i've used hard coded values to login

<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:"/></td>
 
<td style="width: 20%">
<asp:TextBox ID="txtUserName" runat="server"/></td></tr>
 
<tr><td style="width: 20%">
<asp:Label ID="lblPassword" runat="server" Text="Enter Password:"/></td>
 
<td style="width: 20%" >
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"/></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"/><br />
</div>


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");
}
}


If you like this post than join us or share

34 comments:

Shakti Singh Dulawat said...

Hello This is very nice detail by you. Thanks for sharing knowledge.
Thanks
Shakti
http://www.nextmvp.blogspot.com/
http://www.shaktibanna.blogspot.com/


Anonymous said...

"In Global.aspx, in Session_Start event " line you meant Global.asax


amiT jaiN said...

@Anonymous: Yes it should be Global.asax only , sorry for typo , corrected it , thanx for spotting


Anonymous said...

This would also be useful in vb.net.


Anonymous said...

Why not just use the authentication API used by MS?

http://msdn.microsoft.com/en-us/library/9wff0kyh.aspx


Virang said...

Good alternative to Form based authentication.

http://technobird.blogspot.com/


Anonymous said...

If we want to show some pages without login then what will do this code?????
i think always redirect to Login page


Harish said...

I guess this way kind of hard codes and is the classic way of doing it in ASP. ASP.NET has better way of doing it using Forms Authentication. It would be misleading for beginners. Kindly update the article.

Thanks,
Harish


amiT jaiN said...

@Harish : Thanks for the comment, but this applies when you don't or can't use form authentication or membership class


Will said...

I think there could be a couple of drawbacks. One I see is what if you have a aspx page that not secure? For example a contact page. Or about us page. The method I use is a base page class that I usually call SecurePage and I add the validation logic as part of the page life cycle usually in the init method.

-Will


amiT jaiN said...

Hi all

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

amiT


jain4 said...

Hi Amit,
That is a nice code and it helped a lot as a beginner as i didnt wanted to use the Form Authentication.
Now i have couple of questions if dont mind to answer.
The scenario is i am making a website, where i am making a content management system for the admin. Only those files in the admin should ask for login and password. Now with you code i see that every page will ask for login. How do i display the pages which do not require any login.
If you can help it will be gr8.
Thanks.


shubhangi said...

hello Amit,
i want to do multiple edit at once in Grid View,would u help me to get solution.

Thanks
Shubhangi


amiT jaiN said...

@jain4:Hi, Sorry for bit late reply.
According to your scenario, where you only want admin to login and other users to surf with out Login , u need to make some changes in the code i mentioned above

In Global.asax class you need to use this property for the page you want to avoid AuthorizationHttpContext.Current.SkipAuthorization
Like this
if (TestUrl != "Admin.aspx")
{
HttpContext.Current.SkipAuthorization = true;
}

Download and Check the sample i've created for
you

Bypass Authorization for some pages in asp.net
Hope this helps , do let me know your feedback :)


amiT jaiN said...

@shubhangi:
Hi shubhangi please be more specific what's your need , so that i can provide you better solution

amiT


shubhangi said...

hi,

There is grid view,where each row has one check box,and other data,and there single edit button is used in header,i want to edit and update selected rows by clicking on single "Edit" button.i hope u will get it.

Thanks
Shubhangi


hoang said...

Hi every body,

I use MasterPage.
I link some css file and js into MasterPage.
My problem is when put some code in function like code below, my css and js go away, disappear. It seem MasterPage dont load it.

void Application_OnPostRequestHandlerExecute()
{
CheckLogin();
}

I want do the same way to check login but my css and js loaded right.

Please help very urgent
Greatly appreciated!

my email is hoanglt97@gmail.com


amiT jaiN said...

@Shubhangi:

Refer post mentioned below

Edit multiple rows in GrdiView with checkbox


Anonymous said...

Hello I have created the user validation as mentioned above and I have converted the C# code to VB code. Now when I go to my Login.aspx, it shows an error "Session state is not available in this context" and it maps to this line "Dim TestUrl As String = Url.Substring(count)"

Hope you would be able to help me to resole this problem.Thank you.


amiT jaiN said...

@Above:

Please try enabling SessionState in html source of ur Login Page

In page directive set EnableSessionSate = true;

or send me your code i'll look into it


khem said...

thanks sir


Anonymous said...

Need download link for this article or please mail me to dora.meka@gmail.com. The given link is not working..


Term Papers said...

I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards


w3c said...

Nice information, I really appreciate the way you presented.Thanks for sharing..

http://www.w3cvalidation.net/


Anonymous said...

hi amit, thanks for adding this post.. i hav one doubt if login works fine . but after login we create a logout button and clear the session in that event... then redirect to login page.. click the browser back button the page will be displayed this type of errors how to rectify....

thanks in advance...
and the source file is not in the bos.. plz give the source link....


Anonymous said...

cool


Anonymous said...

Hi Amit/All,
I'm new on web application and I'm in trouble to do authentication of users on role basis using 'Forms Authentication'.
The scenario is like that I have 2 roles lets say Role1 and Role2. When user sign in the application using Role1 then this user access only those valid pages for him and same for Role2.
But also there r some common pages for them and they access as it is using their authentication.
Also there r some pages like About Us, Contact Us etc. they need not use authentication.

Also I have a problem after sign out from the site. When I press back button or backspace then the previous authenticate page displayed, this I don't want.

Plz suggest me what I have to do? OR u have any solution for this all problems then let me know.

Thanks in advance

Nishikant Shinde,
shinde.nishikant@gmail.com


Anonymous said...

hi....plz tell me .....its urgent..
mu doubt how to avoid the multiple login using session..........


Anonymous said...

How can i logout page


Jinal said...

hi amit!!!!!i have que. that if multiple user want to sign in at a time how session can be handled.how multiple session can be created?
how can i compare user name & password to database
I am new to asp.net


ar said...

how to validate a page in session for asp.net?


Sathish said...

I am creating a user login form,i need to kw how to create a session for the perticullar user,the fields am using is email and password,but i want to display the user name as a session


amiT jaiN said...

@Sathish : First you need to get username of logged in user from database by writing sql query, then create session variable with that username instead of Authenticate as i created above


Anonymous said...

suppose someone logged in and is very next page after login page. Now if user tries to go back to previous page(login page) then it should show message that you are already logged in. How to do that? Can anyone suggest that please?
How to prevent user to go back to login page once he has logged in......?


Find More Articles