-
Automatically redirect when session timeout exceeded
I have set timeout for my asp.net application to 5 minutes, like web.config below:
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="5"
my question is how to automatically redirect to login page (login.aspx) it timeout exceeded.. please advise ..
many thanks in advance
Regards
Teddy
-
Re: Automatically redirect when session timeout exceeded
You could do something like this:
VB Code:
'' in Page_Load() Event:
If IsNothing(Session("someSessionVarName")) Then
Response.Redirect("someUrl.aspx")
End If
-
Re: Automatically redirect when session timeout exceeded
Thanks for your prompt reply, but what I don't understand is where should I set the first value of "someSessionVarName"? .. sorry I am very new with this . .please advise
Regards
Winanjaya
-
Re: Automatically redirect when session timeout exceeded
Well what are you storing in your Session variable?
-
Re: Automatically redirect when session timeout exceeded
let's say my session variable name is "MyVar" .. how ? please advise .. and TIA
regards
Winanjaya
-
Re: Automatically redirect when session timeout exceeded
Well then in the Page_Load() event of pages, or in one of the events in your global.asax file, you could use:
Code:
If IsNothing(Session("MyVar")) Then
Response.Redirect("someUrl.aspx")
End If
After the Session has expired, the MyVar session variable for that particular user will be lost and will evaluate to vbNullString.
-
Re: Automatically redirect when session timeout exceeded
But I think I should set the initial value of that variable, is it right? if yes .. where should I set that initial value? .. TIA
Regards
Winanjaya
-
Re: Automatically redirect when session timeout exceeded
Well you can set it in a Page_Load() event, or in some part of the global.asax file, or in some entry point to the site, e.g. a login page.
It depends on what you want to store there.
-
Re: Automatically redirect when session timeout exceeded
I tried it already .. for example: I put session("Login")=1 at the page_load of login.aspx .. and also I put below codes on other.aspx:
If IsNothing(Session("Login")) Then
Response.Redirect("login.aspx")
End If
but why it still not working, I meant it is not automatically back to login.aspx when timeout exceeded ..
Regards
Winanjaya
-
Re: Automatically redirect when session timeout exceeded
Why don't you try this.
One page1.aspx, put in this code:
Then on page2.aspx, put this in:
Code:
Response.Write("Session(x) = " & Session("x"))
Keep refreshing page2, and see if it displays the correct data. Try refreshing over the course of 5 minutes...
-
Re: Automatically redirect when session timeout exceeded
I guess you need to put the refresh header on all your pages once the person logs in.
so i beileve it would be something like this:
in your Login.aspx you would have :
and then in all other pages you would add this code
VB Code:
If session("Login") = "1" then
Response.AddHeader "Refresh",CStr(CInt(DateAdd("s",Now + (5 * 60))) ' where 5 minutes if your session time.
'Please check the exact syntax for DateAdd and AddHeader, becoz i am typing it right here and not using Studio. :)
End if
-
Re: Automatically redirect when session timeout exceeded
guess you need to put the refresh header on all your pages once the person logs in.
so i beileve it would be something like this:
in your Login.aspx you would have :
Code:
Session("Login") = "1"
and then in all other pages you would add this code
[code]
If session("Login") = "1" then
Response.AddHeader "Refresh",CStr(CInt(DateAdd("s",Now + (5 * 60))) ' where 5 minutes if your session time.
'Please check the exact syntax for DateAdd and AddHeader, becoz i am typing it right here and not using Studio. :)
End if
'heres an alternative
Code:
If session("Login") = "1" then
response.Write "<meta http-equiv="refresh" content="300;Login.aspx" />"
End If
-
Re: Automatically redirect when session timeout exceeded
First off, you mentioned a login.aspx, so you are obviously requiring users to log in to your application.
Authentication is entirely seperate from session. An authentication is passed along in a cookie (or even a url id for cookieless), so even if a session expires, the person can still be authenticated.
So..
1) What type of authentication are you using?
2) Are you using persistent cookies?
3) Are you using sliding session expiration?
Some Notes:
the best place to check for session or authentication of a request is in the global asax request_state sub.
Out-of-state session where you store session objects in SQL or another process do not signify an end of a session, therefore, the session_End event in the global asax never fires.
-
Re: Automatically redirect when session timeout exceeded
Can you redirect from the Session_End method? I have this, and although I see the debug statement, nothing gets redirected,
Code:
protected void Session_End(Object sender, EventArgs e)
{
Debug.WriteLine("Session timeout.");
Response.Redirect("SessionTimeout.aspx");
}
-
Re: Automatically redirect when session timeout exceeded
Are you using inprocess state? (its the default, but if using sql server or other state containing medium, it will never fire)
If you are using inprocess, are you sure you declared the delegate to that event handler?
Other than that, it should work as expected. Note, that it may not fire until the next request from that session (i haven't work with inprocess much, so i'm unsure exactly when it will fire)
-
Re: Automatically redirect when session timeout exceeded
Yes, I have mode="InProc" in the web.config. I have not declared any delegate to that event handler, guess I haven't read that. However, that method is executing, as verified by the debug I see getting printed to the output window.
Just that the .Redirect business doesn't seem to do anything. .Debug does, though.
FWIW, at first I was using this in every page, and wanted to see if I could get rid of it.
Code:
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
// If it's a new session, then session has timed out.
// Redirect to logon page.
if (Session.IsNewSession)
{
Session.Add("HasTimedOut", "true");
Response.Redirect("Logon.aspx");
}
}
I use the session variable in the logon page to make visible a label that says "Session has timed out".
-
Re: Automatically redirect when session timeout exceeded
What type of authentication are you using?
-
Re: Automatically redirect when session timeout exceeded
I have authentication mode="None" in the web.config. I have a logon page, though, that validates against a database. I'm not sure if that's what you mean. FYI I'm new to the ASP part of .NET, never did regular ASP either.
-
Re: Automatically redirect when session timeout exceeded
Yea, that's what I meant.
Normally, if you are validating against a database, you would use forms authentication which ensures no matter how a person accesses a particular page, they would need to have been authentication to access any page beside the logon page.
So if I had used your app before... and knew the location of your RefundCustomer.aspx, i could simply type it in the url box 'http://localhost/mikesapp/refundcustomer.aspx', and never need to be authenticated because your web config doesnt require it. Whereas, if you set forms authentication, I would have to login because as soon as I hit GO with that url, the .net framework would see I haven't been issued an authentication cookie, and redirect me to the default login page you designated in the web.config.
Anyway... (more to come, thought I let you digest this first)
-
Re: Automatically redirect when session timeout exceeded
Ok guys what if you have a windows authentification, how do you check that the timeout has expire
Ben
Here's the thing. The app that I'm working on is an intranet app so the authentification is been done by a win 2003 server but I need to know when the timeout expires so the new user can't do a thing with the info on the browser if the last user didn't logged off
Any help will be apprecite it
Ben
-
Re: Automatically redirect when session timeout exceeded
Burp. I think I just digested there :)
Quote:
So if I had used your app before... and knew the location of your RefundCustomer.aspx, i could simply type it in the url box
I *thought* I took care of this because (with the code posted above) if it's a new session, it forces you back to the logon page. I did test, and it does seem to work that way.
I still don't get why the .Redirect does not do anything, though.
Edit: I should have clarified that "with the code posted above" I'm referring to is the stuff in Page_Load that I've been putting in every page, and not the business in the Global.asax file.
-
Re: Automatically redirect when session timeout exceeded
Well, the Session_End event will fire when a session expires, but I'm not 100% sure that happens when a request was made from a client, I believe it happens regardless, so if a client shut down their computer.... the event will fire in 20 mins regardless.
So that is not the place to initiate a new session, because the client may not even being using your website anymore.
Here's what I would do:
1) implement forms authentication
2) on the Global.AcquireRequestState event, check
a) if the client is authenticated
b) if the client's session is valid or new..
in the event of an expired session, you would then create a new session for them.
Perhaps the reason why the redirect does not work, because there is no request to handle, so there is no request to redirect.
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by bencis
Ok guys what if you have a windows authentification, how do you check that the timeout has expire
Ben
Here's the thing. The app that I'm working on is an intranet app so the authentification is been done by a win 2003 server but I need to know when the timeout expires so the new user can't do a thing with the info on the browser if the last user didn't logged off
Any help will be apprecite it
Ben
Well, if the next user tried to post the data on that webpage, and the session was expired, you would have to remove the authentication, and redirect them to login again (or in Windows authentication, IE may prompt them with a login box).
I'm not entirely familliar with win authentication, I would imagine it would require a user to re-authenticate if the session attached to a request had expired.
-
Re: Automatically redirect when session timeout exceeded
thanks, but how do you can check if the session has expired?
So is like if session.timeout = 20 then response.redirect? or anything like that?
Also how the authentification can be removed?
I'm pretty new on asp at all (if you haven't noticed :) )
Ben
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by nemaroller
Perhaps the reason why the redirect does not work, because there is no request to handle, so there is no request to redirect.
Looks that way, or at least there's no Response. I tried this code and there's no exception, complaint or whatever, and yet the code just dies as soon as I try to do something with Response.
Code:
protected void Session_End(Object sender, EventArgs e)
{
Debug.WriteLine("Session timeout.");
Debug.WriteLine("Before checking Response.");
if (Response == null)
Debug.WriteLine("Response is null.");
else
Debug.WriteLine("Response is not null");
Debug.WriteLine("Done checking Response.");
...
I see this in the output window
Code:
Session timeout.
Before checking Response.
and then nothing. No unhandled exception. I *guess* that explains why nothing is happening in my failed attempt at Response.Redirect.
FWIW, if I had not seen this behaviour before, I might be worried. Seems to me one should get a null reference exception, object not set to instance, or whatever, if you call a method on a null object. I can't remember the why, but I've written (apparently bad) code that behaved the same way. Could never figure it out and just rewrote in a different way.
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by nemaroller
Here's what I would do:
1) implement forms authentication
2) on the Global.AcquireRequestState event, check
a) if the client is authenticated
b) if the client's session is valid or new..
in the event of an expired session, you would then create a new session for them.
Whoops, forgot to mention that I appreciate the info, nemaroller, this is what I'll try next. Thanks for the help. :thumb:
-
Re: Automatically redirect when session timeout exceeded
That's strange you don't get an error....
You sure aren't handling it a global error handler somewhere?
try appending this line of code to the end of that subroutine
Code:
Debug.WriteLine(Server.GetLastError.ToString());
-
Re: Automatically redirect when session timeout exceeded
Yes, I'm sure I have not written a global error handler, and unhandled exceptions in my code elsewhere behave as expected, bringing you to the stack trace page (or whatever that's called).
I added that line of code to the end of the Session_End method with no change in behavior. The execution just dies the first time I try to do anything with the Response object.
So I put a break point at the first line of code in Session_End. Did a quickwatch on Response and this is what it says:
Code:
Response <error: an exception of type: {System.Web.HttpException} occurred> System.Web.HttpResponse
-
Re: Automatically redirect when session timeout exceeded
try doing a response.write("gi") or something...
but put it in a try-catch, and then write the exception to the debug line.
I'm guessing its gonna say reponse is not valid in this context or something..
-
Re: Automatically redirect when session timeout exceeded
You called that one right:
Code:
System.Web.HttpException: Response is not available in this context.
So, I guess I cannot have a "global" session timeout where I can redirect back to a logon page? Not a big deal, just need to put a couple lines of code in every page.BTW, Session_End does get fired if for example, you're just sitting on a page, so I guess it doesn't really make sense to put there.
Guess I'll go back to plan A. Thanks for all the help, nemoroller, much appreciated.
Mike
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by Mike Hildner
You called that one right:
Code:
System.Web.HttpException: Response is not available in this context.
So, I guess I cannot have a "global" session timeout where I can redirect back to a logon page? Not a big deal, just need to put a couple lines of code in every page.BTW, Session_End does get fired if for example, you're just sitting on a page, so I guess it doesn't really make sense to put there.
Guess I'll go back to plan A. Thanks for all the help, nemoroller, much appreciated.
Mike
Why cant you ?
Create a session time out class and call it when you need to ?
Works a treat...
Code:
class Functions {
//blah here
public function RedirectMe(url as String)
Response.Redirect(url)
end function
}
In one of your pages:
Code:
If Is Nothing(Session("x")) then
try
f=new Functions
f.RedirectMe("www.yahoo.com")
catch ex as Exception
Response.Write("An error Occurred: " ex.toString())
finally
f= nothing
else
'do nothing
end if
-
Re: Automatically redirect when session timeout exceeded
Yeah, that's about what I did - putting a little code in every page. I guess what I meant by the global business was to put it in, say Session_End. I just worry that I'll forget to put the code in a page, and it'd be nice to handle it gloablly.
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by Mike Hildner
Yeah, that's about what I did - putting a little code in every page. I guess what I meant by the global business was to put it in, say Session_End. I just worry that I'll forget to put the code in a page, and it'd be nice to handle it gloablly.
This is global...
My answer to you is to create a reusable class like the one i showed you.
That way you dont have to code it in every page.
-
Re: Automatically redirect when session timeout exceeded
I know slightly off topic, but I'm curious why you would create a class where you have to instantiate it to use the function? looks messy :ehh:
Would it not be better to create a module OR have the functions declared as shared and then just add the class to the global imports on the project?
Also, the Session_End event is just pants, better to use the Cache on a sliding expiration and get it to fire off an event :bigyello:
And for those of you who are trying to use Redirect in the Session_End even, you can't do this. Stop trying!!! please.
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by tailz
And for those of you who are trying to use Redirect in the Session_End even, you can't do this. Stop trying!!! please.
You should have told me that earlier :bigyello:
-
Re: Automatically redirect when session timeout exceeded
nah you were all in full swing, wouldn't have got a post in edgeways
Besides, you might have proved me wrong as I was only 99% sure lol :p
Everyone is clear now why you can't do it right? :ehh:
-
Re: Automatically redirect when session timeout exceeded
I know you can't do it, but I don't know enough about it to know why. I also don't understand why if you try to do something with Response in Session_End, you don't get an exception. Know anything about that?
-
1 Attachment(s)
Re: Automatically redirect when session timeout exceeded
I knew you'd ask so I've done a diagram, picture speaks 1000 words or in this case, probably about 10 words.
Note this took me like 10 minutes of my afternoon off sick so no laughing :-P
hope it helps :D
-
Re: Automatically redirect when session timeout exceeded
and here is an FAQ on session states which I dug up from google that supports my diagram :D
http://www.eggheadcafe.com/articles/20021016.asp
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by tailz
Note this took me like 10 minutes of my afternoon off sick so no laughing :-P
Too late :) - thanks for the explanation.
-
Re: Automatically redirect when session timeout exceeded
:D
but does it clear up your understanding of why you cant redirect in session_end ?
-
Re: Automatically redirect when session timeout exceeded
Yes it does, thanks for the info. My only lingering question is why isn't an unhandled exception raised when you try to do something with Response in Session_End? I guess I would imagine one would generate an exception, and not just have the code die.
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by Mike Hildner
You called that one right:
Code:
System.Web.HttpException: Response is not available in this context.
So, I guess I cannot have a "global" session timeout where I can redirect back to a logon page? Not a big deal, just need to put a couple lines of code in every page.BTW, Session_End does get fired if for example, you're just sitting on a page, so I guess it doesn't really make sense to put there.
Guess I'll go back to plan A. Thanks for all the help, nemoroller, much appreciated.
Mike
Well, like I was alluding to before, the session timeout will occur regardless if the client is even connected to your site. So it would make sense that there probably would not be a Response object available to redirect.
Your problem is more you need a way to authenticate people... that ties into asp.net (forms authentication for example)... and then you don't have to worry about session timeout, because for your app, it probably makes little difference. At worst, the user will have to re-authenticate if they don't touch anything in 20 minutes.
There's a multitude of ways of handling session.. cookieless or with cookies, sliding expiration or not, or even setting session timeout in the future. You could store the session data itself inside a cookie the client passes, thereby eliminating the need to store it on the server. But all of that above really depends on what the expected load(number of users) of the server is, and how content it has to pour down the pipe.
-
Re: Automatically redirect when session timeout exceeded
In a forms app I was making, I built this subroutine
Perhaps you can put it to good use if you implement
forms authentication.
Code:
Private Sub Global_AcquireRequestState(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.AcquireRequestState
If Request.IsAuthenticated Then
Try
If Session("userguid") Is Nothing Then
'we have an authenticated user
'with no current session
'so lets do this
'let's remove their authentication ticket
'then redirect them to logon.aspx
FormsAuthentication.SignOut()
Response.Redirect("logon.aspx")
End if
Catch ex as exception
End Try
End If
End Sub
-
Re: Automatically redirect when session timeout exceeded
Thanks for the info, nemoroller. Let me ask then, is forms authentication the way to go? I've read up on the different methods, just wondering for a real-life app is that's standard practice.
I'm guessing the answer depends on your needs, but I'm so new to this, I don't think I'm the one to judge.
FWIW, the only reason I care about the session timing out and redirecting is because that's a contractual requirement. That is, if the user walks away from their machine, they'll need to re-authenticate after x minutes. Right now, any authenticated user would be authorized for anything, but I'm sure that will change.
Oh, and I'd like to go cookie-less if that's possible, just so I can thwart any opposition, even if that opposition doesn't make sense.
Additional information you may not care about: This application will serving up information on arrested individuals, and there's state and federal guidelines I must follow (I'm in the USA). Hence the need for some pretty decent security.
Thanks,
Mike
-
Re: Automatically redirect when session timeout exceeded
Well,
Windows Authentication is the most secure mode of authentication available in asp.net authentication schemes.
However, it does not work on non-windows machines or machines that are not part of the same domain (or at least would be able to access a list of accounts and their permissions from say active directory services).. its geared toward intranet, which excludes internet use. I assume that may not be problem for you however.
Forms authentication is THE ONLY secure method available for crossing domains and different platforms. Forms Authentication is rather prevalent now in asp.net applications that cross the intranet barrier to the external world. For my part, I coupled Forms with a SSL layer, so usernames and passwords could not be inspected (at least easily anyway).
Most government agencies require Triple-DES encryption, which I believe at minimum is 128bit security. You will want to encrypt your database connection strings no matter where you store them (web.config or registry, or even a flat file).. http://msdn.microsoft.com/library/de...classtopic.asp
With all that said however, Forms and Windows Authentication can be combined, so some aspects of site can still be accessible to a user even if they are not directly connected to the internal network. Of course, VPN is also a good solution to allow workers to access internal networks, in which case Windows Authentication works flawlessly.
Another aspect to consider is securing highly confidential or sensitive data in a subdirectory, secured by its own web.config with its own authentication (so you could have Forms for the initial welcome page, and browsing newsletters or such, and when the user needs to access privy data, they will need to supply their Windows user account to access that data).
In the mean time, the subroutine I listed below is part of a forms authentication implementation, which would log the user out when their session expired - because a client browser could still have a valid authentication ticket - of course that also depends on how long you state that authentication is valid). So that would solve your need to de-authenticate a user after x amount of minutes.
And there are a lot of places security wise that will need to be double-checked as a safeguard. For instance, just because a HTTPRequest posts data to your web application, it does not mean it hasn't been maliciously altered by a third party deflecting the communication. This is where SSL is handy. And of course you know about always validating input fields on the server side even if you do implement client-side validation.
For you right now, the thing to remember is session and authentication are really two seperate independent mechanisms. You should just google for 'Forms Authentication asp.net', or even search some threads here, I'm sure myself and others have given examples of how to implement it.
-
Re: Automatically redirect when session timeout exceeded
two parts really to a forms authentication scheme...
1) The web config part
This goes inside of the <system.web></system.web> tags in your web.config
Code:
<!-- AUTHENTICATION
"Forms" You provide a custom form (Web page) for users to enter their credentials, and then
you authenticate them in your application. A user credential token is stored in a cookie.
Protection tag encrypts and validates the authentication cookie
-->
<authentication mode="Forms">
<forms loginUrl="logon.aspx" protection="All" name="AuthCookie" timeout="22" path="/">
</forms>
</authentication>
<!-- AUTHORIZATION
This section sets the authorization policies of the application. You can allow or deny access
to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous
(unauthenticated) users.
-->
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
2) Adding the authentication ticket
here's an example of how to attach an authentication using forms in a login page.... (logon.aspx)
Code:
'grab the username and passwords from textbox fields, ask
'database if supplied username and password are valid
'if database recognized the supplied login as valid, authorize user
Dim authTicket As FormsAuthenticationTicket = _
New FormsAuthenticationTicket(1, userguid, DateTime.Now, DateTime.Now.AddMinutes(22), False, "")
'encrypt ticket
Dim encryptedTicket As String = FormsAuthentication.Encrypt(authTicket)
'create a cookie and add the encrypted ticket to the cookie as data
Dim authcookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
'add cookie to outgoing cookies collection
Response.Cookies.Add(authcookie)
'redirect user to default page
'go where you want to go
Response.Redirect(FormsAuthentication.GetRedirectUrl(userguid, False))
'if auth failed, don't do a thing, just let the page re-render
-
Re: Automatically redirect when session timeout exceeded
Wow, cool. Thanks for all that info. Will be reading up on forms authentication. I'm in control of all the hardware, network etc., so I guess I could use Windows authentication as well. Time to do some reading.
Again, thanks for the information.
-
Re: Automatically redirect when session timeout exceeded
Quote:
Originally Posted by Mike Hildner
Yes it does, thanks for the info. My only lingering question is why isn't an unhandled exception raised when you try to do something with Response in Session_End? I guess I would imagine one would generate an exception, and not just have the code die.
because its pants and it should do :D