Guys, I am trying to make a website that keeps a cookie active, so long as the user is active in the site. My idea was to create a cookie on the main page of the site, like so:
HttpCookie cookie = new HttpCookie("KeepAlive","1");
cookie.Expires = DateTime.Now.AddMinutes(20);
Request.Cookies.Add(cookie);
If I have this code in my Page_Load event on every page, this should keep refreshing the cookie. If, after 20 minutes, the cookie expires, it will kick them back to the main screen. I just want to make sure I am going about this the right way.
Thanks
I think you should look at using session for that. With Session, you can set a timeout (20 minutes by default), and the rest will occur automatically (updating the active status, etc).
EDIT (more on Session):
By using session, the site user can be identified throughout their experience. This happens automatically, without any need for the developer to code for it or to test that it works.
Session is stored on the server, and is therefore safer (users can modify their cookies)
You can run code at the start, or at the end of any session (using a global.asax file)
Sessions can be setup as cookieless (users may have cookies disabled)
You can store c# objects in session variables so that they are available through the active session (stored in server memory).
I can't think of any more advantages in this case. I invite others to leave comments with their thoughts.
If you really want to use cookies for this, Yes, You are going the right way.
You need to add the cookie to the Response object, not the Request object.
Related
I am having problem in session management in my asp.net. I am logging out of the admin and user account, but as i am pressing the forward button of the browser, the page is redirected again to the User/Admin account. I already destroyed the session i created for storing the username, everytime i am clicking the log out button.
In every page you have you should implement a small if sentence in the Page_Load that checks if the Session is null like so:
if(Session["User"] == null)
Response.Redirect("~/Login.aspx");
Make sure that when you log out, you make sure that the Session is set to null.
If you are using the default template of Visual Studio this may help you:
if(!HttpContext.Current.User.Identity.IsAuthenticated)
{
Response.Redirect("~/Login.aspx");
}
There might be two problems here:
First Problem (Server Side):
Using Session to store authentication and authorization is a poor way to design the application. Use the ASP.NET Authorization and Authentication(FormsAuthentication) framework to do this. This way, your application can use client side cookies to store authentication information, and can allow only certain users to access certain pages in your application(using Authorization).
Session data is lost each time the ASP.NET recycles the application pool(which might happen at random). This is potentially dangerous and can cause NullReferenceExceptions during usage.(This happens if Session management is inproc which is the default)
Second Problem (Client Side):
Usually, the browser caches the page, so the Page_Load will not be executed on the server side. To work around the problem, you can add this code in Page_Load event on each page if you want to(or add it to a Master Page) :
Response.Buffer=true;
Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);
Response.Expires =-1500;
Response.CacheControl = "no-cache";
And, then, the Authorization|Authentication part of ASP.NET will gracefully redirect you to Login.aspx page, if, the user has been logged out.
Using some more code, you can even redirect to the homepage for a particular user, if the user is already authenticated based on a certain roleID.
We have a website that has a 20 minute session timeout and our users want a 10 minute session expiry warning. At the moment we're using a control which kinda does the job but it isn't AJAX aware and so pops up even if the user has been doing stuff.
I have an idea to get around this by just polling the server every 2 minutes to find out how long the user has left on their session. But after research i can not find out if its possible to say "This request shouldn't refresh the timeout", which is crucial as the act of polling would inadvertently refresh the session timeout.
Is this possible, or am I going about it the wrong way?
I think the only reliable way you can do this is to modify your ajax javascript to extend the timeout on your existing script.
You could use the disable session state for a page then modify your app to store the last access time for a user in the db. poll the session-less page to find out when the user last did something.
Either way you'll have to make extensive changes across your app.
If your session has a fixed 20 minute expiry, then it won't get extended by refreshing a page. However, if you want to have a script on your page to alert users of their imminent session expiry, then you'll need to set a client side script (presume Javascript) and kick it off on page load?
<script type="text/javascript">
function alertSessionTimeout(){ alert("Your session is about to expire. Please refresh the page.") }
window.setTimeout('alertSessionTimeout', 10*60*1000);
</script>
what about TWO web applications accessing the same database? in the first, the main, application you write last access time to database, and the second application is polled via ajax to get inactive time base on last access time...
In polling the server you see how long is left you would be resetting it back to 20 minutes. You would need to make sure the request does not attach the session cookie to prevent this. In doing so you create another problem in that you can't access the user session.
An alternative is just do in JavaScript page load using SetTimeout.
It seems that some people are confusing Session state with Forms Authentication ticket expiration. Session state has an automatic sliding expiration - if session is set for 20 minutes and after 19 minutes of talking to your friend in the office, you request a page, you get another 20 minutes.
This is an old question, but I have a similar problem and had this idea for a solution.
Upon each page request that uses the session, your session gets refreshed. Into the application cache, put key=sessionId and value=DateTime.Now.
Create a web service (.ashx or what have you) that does NOT use session state, but ideally is authenticated using Forms Authentication or some other authentication scheme. Your javascript, which is counting down the time until session expiration, will call this web service shortly before the session expires to see if the session is really going to expire.
I'm thinking the web service should return something simple like a 2 if the session is expired, 1 if the session is about to expire, or 0 if not. Return random [0,1,2] if the service is called by a user with an unknown or invalid SessionId cookie -- this would hopefully prevent valid sessionId discovery by an attacker who gets a Forms Auth cookie.
I investigated decompiling the built-in SessionProvider to see if I could access the session to discover the expiration without triggering a refresh. But doing so is dependent on the type of session provider being used, so if you ever move from, say, SQL Server session provider to Redis, you have to rewrite it.
I would like to know can we delete cookie from cookies collection what we have created in asp.net website.I tried & find Expiration Logic.It works but it shows in browser cookie.
Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(-1);
Is there any other way by this we can delete cookies from collection so it will not show in browser cookies.
Please help me to solve the issue.Thanks in advance.
From the documentation:
You cannot directly delete a cookie on
a user's computer. However, you can
direct the user's browser to delete
the cookie by setting the cookie's
expiration date to a past date. The
next time a user makes a request to a
page within the domain or path that
set the cookie, the browser will
determine that the cookie has expired
and remove it.
So, your strategy is the right one, and the cookie should disappear from the browser once the response is received.
I'm not sure you can delete the cookie since you don't have access to delete anything on the client computer. All you can do is basically what you are doing, that is invalidating the cookie for your application. I think it is up to the client software to decide if the cookie should be deleted or not, all you can do is set the timestamp as you are doing and that means that you will no longer accept that cookie.
i want to create a global session which will stay active until and unless we manually kill it. how to do this in asp.net with c#
what i am doing is
HttpContext.Current.Session["UserID"] = someValue;
but in this way the session is lost after some time.
You can set the timeout in web.config under system.web -> sessionState -> timeout. Not sure if you can have an infinite session though.
Also, you might be interested in the Application object which stores things in the "application's session" instead of the user's. Comes to my mind because you speak of a "global" session.
What's the application for this? Sounds like you're actually trying to use the session as a persistent storage, which will however only seemingly work even if you manage to set timeout to never or 5 years or whatever - because sessions will be "timed out" once the application is restarted. You might still get around that, but you might be better off looking for real persistence solution like a database. I may be totally off guessing your application for that of course.
Store the data in the Application state rather. It will stay there till you remove it, or the app dies/recycles/ends.
Usage:
HttpContext.Current.Application["Foo"] = "bar";
As nicolas78 says use session timeout configuration property to control the session expiry after user inactivity. In case, you are facing a requirement where session should be active as long as browser is open, there are two ways -
Use cookie to store some token and then re-construct your session state using the token if session gets expired. For example, user details can be recovered from user store if user id is stored in token. At worst, you may have to move your entire state to the database.
Keep the ASP.NET session state but keep it alive by firing AJAX requests from browser. I would suggest to fire such request after n/3 interval where n is your session timeout (ensuring at least three requests are made so even if two gets lost or falls on edges, one gets through).
Perhaps you're after profiles?
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
Profiles live beyond the session and are usually used to store per-user settings that the user can edit, such as their contact details and application preferences.
Profiles can be used with both anonymous and authenticated users. When an anonymous user signs in, their anonymous profile can be migrated into an authenticated profile (i.e. one that is attached to their user name).
Good walkthrough here: http://quickstarts.asp.net/quickstartv20/aspnet/doc/profile/default.aspx
basically, if cookeis are disabled on the client, im wondering if this...
dim newCookie = New HttpCookie("cookieName", "cookieValue")
newCookie.Expires = DateTime.Now.AddDays(1)
response.cookies.add(newCookie)
notice i set a date, so it should be stored on disk, if cookies are disabled does asp.net automatically store this cookie as a session cookie (which is a cookie that lasts in browser memory until the user closes the browser, if i am not mistaken).... OR does asp.net not add the cookie at all (anywhere) in which case i would have to re-add the cookie to the collection without the date (which stores as a session cookie)... of course, this would require me doing the addition of a cookie twice... perhaps the second time unnecessarily if it is being stored in browsers memory anyway... im just trying not to store it twice as it's just bad code!! any ideas if i need to write another line or not? (which would be)...
response.cookies.add(New HttpCookie("cookieName", "cookieValue") ' session cookie in client browser memory
thanks guys
This MSDN article seems to indicate that there is no built in mechanism for compensating with the user disabling cookies. It also indicates that session state does not work without at least some level of cookies being enabled.
I thought that there was a mechanism for passing a query variable for the session id but skimming the article (quickly) I did not see this.
Hope that helps.
EDIT: It does say that you can use cookieless sessions (I thought you could). They use a separate mechanism to embed session ID in the pages and url links.
To follow up on GrayWizardx's reply, much of what was said is completely accurate.
If you are using a Cookie'd version of Session, and cookies are disabled then you are out of luck. But you have the option to have a cookieless version of the Session, which adds a string to the URL that shows the users session id. This is very ugly looking, and has always concerned me from a security perspective.
So you have three options (that I can think of off the top of my head):
1. Require cookies. This is not a bad thing, especially if your site is one that would have requiring cookies as normal.
2. Use ViewState.
3. Pass information from page to page within the URL. This, again worries me from a security perspective.