ASP.NET MVC Application Timeout Not Working - asp.net-mvc

In my Web.config file, I have been trying to set the session timeout. I used the following code:
<configuration>
<system.web>
<sessionState timeout="1"></sessionState>
</system.web>
</configuration>
When I ran the app, the timeout was still set to the default 20 minutes. Trying to figure out why the settings are not applying. Please help! Thanks!

Don't be confused between ASP.NET session timeout (which is what you set) and Forms Authentication cookie timeout which is something entirely different and controlled by the <forms> tag:
<authentication mode="Forms">
<forms
loginUrl="/login"
timeout="1" />
</authentication>
ASP.NET session uses cookies to track users (it has nothing to do with authentication) and associate their unique id with a hashtable stored on the server. Forms authentication on the other hand is a means of tracking authenticated users in ASP.NET. It uses cookies but it is a different cookie than the ASP.NET session.

Related

Cookie expires or session timeout too soon

I have code like this which is run when a user is authorized:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
email,
DateTime.Now,
DateTime.Now.AddMinutes(120),
true,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
faCookie.Expires = authTicket.Expiration;
Response.Cookies.Add(faCookie);
I then redirect to a controller/Action that has the Authrize attribute:
[Authorize]
public class ProductsController : Controller
{
I have the following in web.config:
<authentication mode="Forms">
<forms loginUrl="~/Home/Unauthorized" timeout="2880" />
</authentication>
<sessionState timeout="120"></sessionState>
However users are complaining of session timing out or redirecting Home/Unauthorized after a couple of mins of inactivity.
what could be causing this, what else should i check?
A couple of thoughts before I go into a possible solution of why your logins are expiring. First, the FormsAuthentication cookie and SessionState are two different things completely. You can have one or the other, or both or neither. As a result, the timeouts for these two items are also not related.
The FormsAuthentication cookie is an encrypted cookie that contains some basic information such as the user name and an expiration value. The .NET application uses this cookie once a user has authenticated to know if the user is authorized for certain resources.
What controls the encryption and decryption of the FormsAuthentication cookie is the MachineKey for that web application on IIS. The MachineKey is a set of keys used to encrypt and decrypt the cookie. By default, a web application on IIS is set to AutoGenerate the machine key. What this means is that when an application starts, a random machine key is generated. If an application recycles, you get a new machine key. Additionally, if you are hosting on a shared provider, the web host will typically have your application load balanced, meaning hosted by more than one server. Each one of those servers will auto generate a machine key.
If your web application is on a load balanced scenario, then each machine in the web farm cannot decrypt the other's encrypted cookie. This will give the appearance of "being logged out". The example of this is logging in on web server A, then a subsequent request goes to web server B. Web server B does not share a machine key with web server A and cannot decrypt the cookie, sending the user back to the login page.
The solution is to define the MachineKey section in your web.config so each instance of IIS will use the same keys as well as if the application pool recycles, you still have the same machine key.
Here would be an example machine key (use the .NET 2.0 version) that you could place in your web.config
<system.web>
<machineKey validationKey="EBC1EF196CAC273717C9C96D69D8EF314793FCE2DBB98B261D0C7677C8C7760A3483DDE3B631BC42F7B98B4B13EFB17B97A122056862A92B4E7581F15F4B3551"
decryptionKey="5740E6E6A968C76C82BB465275E8C6C9CE08E698CE59A60B0BEB2AA2DA1B9AB3"
validation="SHA1" decryption="AES" />
</system.web>
Additional thoughts are that your expiration in your web.config (2880) and what you are actually setting the expiration to be (120) do not match. You may want them both to match.
If you are running behind a load balancer you will want to ensure that the web farm is using a consistent key as pointed out by Tommy's answer.
Other things to check will be that the IIS metabase settngs for each server are identical. They need to have the same path and ID.
You will also want to look at holding session out of proc (your web.config looks like in proc) which is susceptible to network outage and random app recycles.
Basically a summary of this link.
http://msdn.microsoft.com/en-us/library/vstudio/ms178586(v=vs.100).aspx
If you can post more of your config if possible and give more detail about your environment setup it will be easier to point you in a more focused direction.
Try This one:
web.config Code:
<system.web>
<httpRuntime maxRequestLength="40000000" useFullyQualifiedRedirectUrl="true" executionTimeout="600000" />
<authentication mode="Forms">
<forms loginUrl="~/Home/Unauthorized" timeout="2880" cookieless="UseCookies" />
</authentication>
</system.web>
This will help you.

After adding the SessionState tag in web.config file, URL gets changed.

I am developing MVC application.
I have added the below code in web.config to handle session.
<system.web>
<sessionState mode="InProc" cookieless="true" timeout="30" />
</system.web>
after adding this code , when I run the application , I get the following url in browser.
http://localhost:65344/(S(egpaesodxcoii0dxtczyi10c))/Login/LoginUser
I am confused about (S(egpaesodxcoii0dxtczyi10c)) this part.
if I remove this SessionState tag
<sessionState mode="InProc" cookieless="true" timeout="30" />
from web config then it start appearing normal like below
http://localhost:65344/Login/LoginUser
whats the issue ?
There is no issue.
When you use Cookieless sessionstates, the user's sessionId is embedded in the url. If you do not want this embedded you should consider setting Cookieless to false.
I recommend you have a read of this documentation it should outline the differences between the two.
Hope you find this useful.
There are two ways that session state can store the unique ID that associates the client with a server session: by storing an HTTP cookie on the client or by encoding the session ID in the URL. Storing the session ID in the cookie is more secure but requires the client browser to support cookies.
For applications that allow clients that do not support cookies, such as a variety of mobile devices, the session ID may be stored in the URL. The URL option has several drawbacks. It requires that the links on the site be relative and that the page be redirected at the beginning of the session with new query-string values, and it exposes the session ID right in the query string, where it can be picked up for use in a security attack.
You are encouraged to use the cookieless mode only if you need to support clients that lack cookie support.
So setting : cookieLess to False will work for you
<system.web>
<sessionState mode="InProc" cookieless="false" timeout="30" />
</system.web>

ASP.NET Session Times out more earlier than expected

My current running configuration looks like this
<sessionState mode="InProc" timeout="30" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" protection="All" name="Auth_Cookie" path="/" slidingExpiration="true" timeout="30" />
so I expect it to at least let the user be logged in for half an hour (if he does not make any requests)
but the session time out is hit like after 3-4 minutes if the user is not active. I mean global.asax's Session_End event is hit in this time and then in Application_PostAcquireRequestState event I check if any session variables are null and if they are then I sign the user out and redirect him to the log in page. I cant see what is the problem. Am I misunderstanding how this whole works ? what should I do in order to achieve what I want. Thanks in advance
From your comment:
I am constantly rebuilding the solution. is that be it ? can it be
clearing session variables ?
So basically you are recycling the application pool killing everything stored in the session. The biggest problem with ASP.NET Session is that by default it is stored in-memory:
<sessionState mode="InProc"
This has the drawback that if the application pool is restarted you will lose everything you stored in it. And don't forget that the application pool could be restarted by IIS at any time. For example after some period of inactivity or if some CPU/memory thresholds are reached. Also if you deploy your application in a web farm, InProc session simply won't work because the nodes of your farm cannot share session information.
All those drawbacks are the reasons why I never use ASP.NET Session in my web applications and simply put this in my web.config:
<sessionState mode="Off"

asp.net mvc forms authentication with no membership

I have a following scenario: user logs in using google account and then I call FormsAuthentication.SetAuthCookie(name, true);. In my web.config I have
<authentication mode="Forms">
<forms cookieless="UseCookies" name=".someName" slidingExpiration="true" timeout="10080"/
</authentication>
And that's it, no membership provider, no dbo.aspnet_* tables. And that would be fine except sometimes (I don't know why) even when user doesn't close browser and sends requests periodically he becomes non-authenticated again. Can anyone explain why?
And what should I do to make authentication persistent? Would be great if solution wouldn't involve sql server as there isn't any.

How do I time out a ASP.NET MVC logged in user?

How do I time out the session a ASP.NET MVC logged in user after about 5 mins or so forcing him to have to login in order to continue?
Since MVC is just like WebForms in that they both run on ASP.NET and assuming you're using Forms Authentication you can either:
Force the user to logout with FormsAuthenitcation.SignOut() which will clear their authentication cookie; or
Set the forms authentication timeout value (default is 30 minutes). For example:
<system.web>
<authentication mode="Forms">
<forms timeout="5"/>
</authentication>
</system.web>

Resources