Asp.net forms authentication cookie not honoring timeout with IIS7 - asp.net

Authentication cookies seem to timeout after a short period of time (a day or so). I am using Forms Authentication and have the timeout="10080" with slidingExpiration="false" in the web.config. With that setting, the cookie should expire roughly 7 days after the user is successfully authenticated.
This worked as advertised with IIS6, but when I moved the site to IIS7, the cookie expires much quicker. I've confirmed this behavior on multiple machines with IE and Firefox, leading me to believe it's an IIS7 setting.
Is there a hidden setting that is IIS7 specific related to authentication? All other authentication types are disabled for the website, except for anonymous user tracking.

The authentication cookie is encrypted using the machineKey value from the local web.config or the global machine.config. If no such key is explicitly set, a key will be automatically generated, but it is not persisted to disk – hence, it will change whenever the application is restarted or "recycled" due to inactivity, and a new key will be created on the next hit.
Resolving the problem is as easy as adding a <machineKey> configuration section to web.config, or possibly (preferably?) to the machine.config on the server (untested):
<system.web>
...
<machineKey
validationKey="..."
decryptionKey="..."
validation="SHA1"
decryption="AES"/>
...
</system.web>
Google generate random machinekey for sites that can generate this section for you. If your application deals with confidential information, you might want to create the keys yourself, though.

My understanding is that cookies are expired by the consuming party - the browser, which means that IIS has no say in this

Set session state configured in IIS as
In Process
Use Cookies
Time out = your required time
Use hosting identity for impersonation
Also set EnableSessionState to true (which is default too)
And most importantly run the app pool in classic mode.
Hope your problem will solve.

First of all i must say that these "guidelines" are generic and not iis-7 exclusive.
In web.config under <system.web>
you either have <sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" timeout="130" cookieless="false"/> (which requires the ASP.NET Session State Server service running on localhost)
or <sessionState mode="InProc" timeout="130" cookieless="false"/>.
The main difference is that in InProc that session state data are placed in the application process itself. In the other setting a different service is doing the storage, and you application just polls it to get the required data.
Having used both (as well as sql-server session state mode) the InProc is the least reliable but the fastest. The Sql-server is the most reliable and the slowest and the StateServer mode is somewhere in the middle being unreliable only in the case of a power/system failure. Having said that, i must say that for site with a low request count the performance penalty is negligible.
Now, my experience has shown that InProc is quite unpredictable on its stability; i used to have the same problem with you. I was able to extend the stability of the application by tweaking the settings of the application pool, i removed the problem altogether by switching to SessionState (which also allows to bring down the application and not lose session state data).
The reasons that you may suffer from application/session stability:
IIS and application pooling. Each virtul directory of a website is assigned to an application pool (by default to "DefaultAppPool") which has a series of settings amongst which you define the interval that the process is "recycled" - and as such preserve system resources. If you don't change the settings the application may trigger one of the criteria for the process recycler, which means that your application is busted
Antivirus.
In a ASP.NET application if the web.config (and any child .config files the application depends on) file is touched the application is restarted. Now there are cases where an antivirus program may touch the web.config file (say once a day?) and as such the application is restarted and session data is lost.
Bad configuration
Specifically for Forms Authentication the time-related settings and behavior always where dependent on the web-session with the auth-session being under the web-session.
What i don't know is if the Forms Authentication module depends only on Session domain or if it also places data in the application domain as well. If the second is the case then you may have to disable all recycling settings in the Application Pool as well as checking again configuration/antivirus and who stores the session data.

I recently had the same problem where my site was timing out every 20 minutes even though I set the session timeout to 2 hours. I found that it was because IIS worker process was timing out every 20 minutes: http://technet.microsoft.com/en-us/library/cc783089(WS.10).aspx

Related

Asp.net Session expiring automatically after few seconds

When user login i am storing user_id in Session variable and on second page i am checking on page load if user_id exists then fine, otherwise redirect to sign in page but when i login and and redirected to next page after few seconds when i refresh page my session is null there and i am redirected to sign in page its happening in whole application i have tried all solutions but all in vain
Another thing is that application working fine on development server and also on local IIS in LAN but on live server this issue is occurring.
Kindly suggest solution, i am also defining session time out in minutes and mode in Proc in web.config.
Thanks in advance
If you are using InProc session state mode and multiple worker processes in the application pool then Session might expire automatically after few seconds as data loss can occur if different requests for the same session are served by different worker processes.
In my case, I am using InProc session state mode with Maximum Worker Process set to 4 hence session was expiring.
Setting Maximum Worker Process = 1 solved it.
You can add <httpRuntime delayNotificationTimeout=""/> in your web.config. see more
OR
Try this
<authentication mode="Forms">
<forms loginUrl="/loginurl" timeout="2880" />
</authentication>
try this in web.config
<configuration>
<system.web>
<sessionState mode="InProc" timeout="90"></sessionState>
</system.web>
</configuration>
One session issue I just ran into, which may help here, is that users from certain companies would have their sessions end fairly quickly but other users had no problem. After doing a lot of testing, I found that users connecting to the website from their office were having problems but the same user connecting from home had no problem.
Their company is setup to use a single IP (or set of IPs) for all out bound web requests. Well, this company had multiple IPs for out-site access and that IP changed (or could change) with each request. This would reset the session on my website and log them out.
I am still in the process of implementing a fix or a check for this so I can't give you a fool proof fix, but it is something to look into. This would explain what is happening to you.
Any chance you're using a cluster of servers? Network load balancing might reroute the client to a different server every time. If so, either the NLB has to be reconfigured to keep a client on a single server or set up session sharing.
Also check that the application pool doesn't have some obscene rule to recycle itself too often.

Asp.net forms authentication IIS 7.5 with multiple servers

I have a Asp.Net web application running on Windows 2008 R2 (IIS 7.5). I have two servers WWW1 and WWW2 and the DNS records are set up for round robin DNS for "www". I increased the AppPool timeout and the Session State timeout settings so users don't get logged out after 20 minutes. However I've noticed users are getting logged out randomly. I think what is happening is the user goes to www.foo.com and logs in and then afterward some time the round robin navigates them to the opposite server in the cluster (WWW1 or WWW2) where the cookie was not created and therefore prompts them for a login.
How can I get this to work and still keep my high availability solution using round robin DNS?
The issue here is each server maintains its own session state in memory and doesn't know about sesssions created on the other server.
To get around this, instead of using the default InProc session state provider you'll need to use the StateServer or SQLServer session state providers.
To do this you'll need to make sure the ASP.NET state service is running on one of your servers and then you'll need to add the following configuration item to the system.web section of your application's web.config file, replacing 'SampleStateServer' with the name of the server you are running the ASP.NET state service on:
<sessionState mode="StateServer"
stateConnectionString="tcpip=SampleStateServer:42424"
cookieless="false"
timeout="20"/>
Microsoft's documentation on this is available at http://msdn.microsoft.com/en-us/library/ms178586.aspx
Because you are running this in a web farm you'll also need to make sure the web applications on both servers are using the same encryption keys.
For this you'll need to set a machineKey entry in the web.config whic involves adding an entry like the following to the system.web section of the web.config:
<machineKey validationKey="4D0590A0E4DE163BAD0EEEB6747467D770CD5FB2EA95BF02B27787A45CA579DECB01E2A1F16563DBAB44C1C0E54C7E53D65F2A7D0FDF378F4D3702B3F2C8B165" decryptionKey="928771D7B1B8C32608F56AC428EC5902985F6FB2E6E9A78733B6EAA493FA13F5" validation="SHA1" decryption="AES" />
There are several websites which will generate keys for you. I typically use http://aspnetresources.com/tools/machineKey
If you want to use the SQLState provider instead, http://msdn.microsoft.com/en-us/library/ms178586.aspx has all the configuration information under the 'Sql Server Mode' section of the page. The setup for that is slightly more involved as you have to configure a database in which you will store the state.

Increasing Session TimeOut

Site hosted via IIS 7.0
I would like to set my session time-out to 9 hours in my ASP.NET application.
This has been set at web.config
<sessionState timeout="540"></sessionState>
But, as I understand, if the timeout is set as 20 minutes inside the IIS where the website is hosted, setting an extended session state will be of no use.
Firstly, I would like to confirm whether this assumption is right.
The problem is that I do not have access to the IIS of my shared hosted web server.
Now, after some research, I came up with another solution in code project. This sounds like a wonderful idea. The idea is to insert an iframe to master page. The iframe will contain another page with meta refresh less than 20 minutes.
Response.AddHeader("Refresh", "20");
This idea seemed good for me. But the article is 7 years old. Plus at comments section a user complaints that this won't work if the page is minimized and I am worried that the same happens when my pages tab is not active.
I would like to know these things
Whether the refresh method will work for my scenario , even if the page is minimized?
Are there any other methods that could increase session time out that overrides IIS timeout setting?
Also I read some questions in Stack Overflow where the answers state that the IIS session timeout is for clasic ASP pages. Then why is not my extended timeout not firing?
Firstly, I would like to confirm whether this assumption is right.
Yes, this assumption is absolutely right in case you are using in-memory session state mode. In this case the session is stored in memory and since IIS could tear down the AppDomain under different circumstances (period of inactivity, CPU/memory tresholds are reached, ...) the session data will be lost. You could use an out-of-process session state mode. Either StateServer or SQLServer. In the first case the session is stored in the memory of a special dedicated machine running the aspstate Windows service and in the second case it is a dedicated SQL Server. The SQL Server is the most robust but obviously the slowest.
1) Whether the refresh method will work for my scenario , even if the page is minimized?
The hidden iframe still works to maintain the session alive but as I said previously there might be some conditions when IIS unloads the application anyway (CPU/memory tresholds are reached => you could configure this in IIS as well).
2) Are there any other methods that could increase session time out that overrides IIS timeout setting?
The previous method doesn't increase the session timeout. It simply maintains the session alive by sending HTTP requests to the server at regular intervals to prevent IIS from bringing the AppDomain down.
3) Also I read some questions in Stack Overflow where the answers state
that the IIS session timeout is for clasic ASP pages. Then why is not
my extended timeout not firing?
There is no such thing as IIS session timeout. The session is an ASP.NET artifact. IIS is a web server that doesn't know anything about sessions.
Personally I don't use sessions in my applications. I simply disable them:
<sessionState mode="Off"></sessionState>
and use standard HTTP artifacts such as cookies, query string parameters, ... to maintain state. I prefer to persist information in my backend and retrieving it later using unique ids instead of relying on sessions.

Updating an existing asp.net website kicks off users

When I update an ASP.NET Website [note: it's not a Web Application] running on a customer server by overwriting it with the latest version it currently kicks all the users off.
I'd prefer to be able to deliver a new version of a site without kicking off users - is there a way to minimise the chance that users will get kicked off? [apart from the obvious one of waiting for a time of low-usage]
If I moved from InProc to Session State I guess this might do the trick - but is there any other method?
Chaning away from InProc Session State should help.
The problem now is that any time your app is reset in IIS (overwriting the web.config will cause a restart), the IIS Worker process restarts and clears your session info.
Check out this MSDN Page to read the limitations of In-Process Session State:
Session State - MSDN
I think additionally to what you are suggesting, it will be appropriate to display an "update in progress..." page instead of kicking off users. You can do that by changing your web.config file.
Session IDs are valid for the lifetime of the application pool, or until (I believe) 20 minutes following the last page request from the client in question. This is configurable in web.config:
<configuration>
<system.web>
<sessionState
cookieless="false"
timeout="20"
</sessionState>
</system.web>
</configuration>
If the application pool is recycled, files within the application are updated, etc, your session IDs will be invalidated. For this reason it is considered wise to deploy your site during off-peak hours.
Design your application to not rely on the existence of session state variables. Use cookies for authentication (or integrated auth) and check for session variables as you use them; reload them if they don't exist.

ASP.NET Application Restarts Too Much

I have an ASP.NET WebSite which restarts in every 1-2 hours in a day so sessions and other thing are gone and users are complaning about it, because they open a page and do something for 20 minutes and when they submit it, a nice "we are sorry" page is there.
I don't do anything which restarts the application (changing the web.config, changing the files, or even other buggy things like deleting a folder in App_Data which normally shouldn't cause a restart).
Can it be related with Server's hardware? It is not much powerful.
I guess this is recycling.
App pools in IIS get recycled by default - either after a timeout, or after "n" hits.
This should be expected, and is part of the normal processing (although it can be disabled in the app-pool configuration; IIS6 | IIS7).
The fact that this breaks your app suggests that you are using a lot of things like in-memory sessions. Consider moving these to database backed implementations. Apart from withstanding both app-pool restarts and server reboots, this can allow you to scale the site to multiple servers.
Check this blog post about some possible causes for appdomain recycles. There are many possible causes.
If you are unable to fix the problem you could switch from in-process session state to eiter a session state server or to storing session state in a database. Both options are easy to set up and works quite well, but there is a performance impact (between 10-20% I think). There is a nice article here about how to setup a session state server.
Sounds like the app is being recycled or process is failing.
Check app pool settings http://msdn.microsoft.com/en-us/library/aa720473(VS.71).aspx
and event viewer.
Since you mention that your server is small, you might check to see if your worker process is consuming more memory that you have set in your processModel in machine.config. That can cause a reset.
Are you sure that the ASP.NET application actually restarts? Or do you think that it happens because of the lost Session and such?
What is your application's (and IIS') Session timeout variable? The default value of the timeout is 20 minutes, so that's why I am asking. You can set the timeout in your web.config as follows:
<system.web>
<sessionState timeout="120"/>
</system.web>
But apart from that, there are also places inside IIS itself where you can set it. In the case of IIS6 those places are:
Properties of a virtual directory > Home Directory (tab) > Configuration (button) > Options (tab) > Session timeout
Properties of a virtual directory > ASP.net (tab) > Authentication (tab) > Cookie timeout
I'm not sure whether or not both are actually needed, but I usually set both to the same value as I set it in my web.config.
Is there any indication of the cause of the restart logged in the Event Log?
Do you have any anti-virus software running on the server. A change to the web.config will cause your application to restart afaik so in some instances anti-virus software passing over the web.config might alter the attributes on the file which could be causing the reset.
Try disable any AV software or exclude the web applications directory from the AV auto scanning.

Resources