ASP.Net MVC: Session duration? - asp.net

Due to the complex business logic, I had to implement myself the authentication. I'm storing the authentication with:
FormsAuthentication.SetAuthCookie(identifier,false);
The False is to indicate that we don't want to have persistent cookie
I've to also store in session some informations(one information that the user has to enter to login, indicating for which set of data he wants to access).
I'm storing those data through model binder.
It's working fine most of the time. But sometime after an inactivity period, we are still logged but we don't have any data in session.
I would like that the duration of my session is the same than the login session, to avoid this kind of "I'm logged but I've lost some data in the session".
I don't need/want to have a persistent connection.
How should I proceed to have this system?

I believe the FormsAuthentication uses its own timeout. You can configure your web.config accordingly:
<system.web>
<authentication mode="Forms">
<forms timeout="50"/>
</authentication>
<sessionState timeout="50" />
</system.web>

In fact, There was a Session timeout by default in the IIS Application pool, so, to avoid this problem:
Go on IIS Manager
Go on the ServerName/Application Pools tab
Right click on the concerned application pool
Click on Advanced Settings,
In the section "Process Model", put an higher value in the "Idle Time-out"(this is in minutes
Click on OK
Restart the application pool
For me, this + the Yannis config(setting the same value for the form timeout+session state timeout) worked.

Related

ASP.NET MVC - Erasing session data after fer minutes of inactivity

In my web application, i often can see, that when i am not doing anything for a few minutes, and then i come back, and refresh the page - i am still being logged in, but my session data is all gone!
On the login() action i am setting up few Session[] objects that are necessary for a page to work correctly. I have no idea why is it doing so, but i need it to log user out whenever it clears his session data.
I have read about setting <sessionState mode="InProc" timeout="20"/> but will this timeout refresh everytime i refresh the page? Or will it run out after 20 minutes from the time i logged in? What if i make this timer bigger than i have on keeping the user online?
Posting back to the server will keep the session alive for longer. It's a sliding expiration. There are two ways to handle from the client, which the client is not aware of this 20 minute timeout:
Create a timer using client javascript that redirects to the logout page when 20 minutes is hit
Whenever a postback happens, check if the session expired (which can be done in a variety of ways, such as checking Session.IsNewSession, see if your objects are lost, etc.) and then redirect to the logout handler before processing the request.
I assume you are using Forms Authentication. Is that correct? If so, you need to have your Forms Authentication ticket's timeout match the Session timeout.
The user stays logged in through a process that is more complicated than it first seems. A cookie is stored in the user's browser that is called the Forms Authentication Ticket. If the user stays idle past the session timeout limit, the server will discard the session. But on the next request, the Forms Authentication Ticket is passed back to the web server. The server validates the ticket, and if it is still valid, the user is logged back in.
As you can see, the user's session is not restored. If you want that behavior, you would have to detect that condition and restore the session yourself.
The solution is to set the Forms Authentication Ticket's timeout to be the same as the Session timeout. You accomplish that in your Web.config file, as explained here:
<system.web>
<authentication mode="Forms">
<forms timeout="20"/>
</authentication>
</system.web>
The timeout value is in minutes. Once the Forms Authentication Ticket's timeout is hit, the user will be logged out. This operates independent from the session's timeout, but if they are the same, they will expire at roughly the same time. If you want to be completely safe, set the Forms Authentication Ticket timeout to be a little shorter than the session timeout. The user will be logged out before their session times out. When they log in again, they will get a new session. The old session will eventually time out on its own.
Try checking this:
Q: In Proc mode, why do I lose all my session occasionally?
A: Please see the "Robustness" section in the "Understanding session
state modes" section of of this article.
Robustness
InProc - Session state will be lost if the worker process
(aspnet_wp.exe) recycles, or if the appdomain restarts. It's because
session state is stored in the memory space of an appdomain. The
restart can be caused by the modification of certain config files such
as web.config and machine.config, or any change in the \bin directory
(such as new DLL after you've recompiled the application using VS) For
details, see KB324772. In v1, there is also a bug that will cause
worker process to restart. It's fixed in SP2 and in v1.1. See
KB321792.
Source - http://forums.asp.net/t/7504.aspx/1

Sessions and auth in asp.net

While deveoping a site (using Forms authentication and InProc sessionstate) a frequently run into a scenario where I lose the variables stored in Session (such as Session["myVar"]), but my auth-session remains valid.
This results in some wierd behavior on my site.
Why is this happening and what can I do to prevent diffrent lifecycles for my auth and my session variables?
In Asp.Net a Session and "Being logged in" are not the same thing.
Both are (usually) controlled by cookies, but the cookies are separate.
To control how long a Session is kept alive, please see answer by Jonas T.
To control how long a user remains logged in, you can use the timeOut on the <forms ... /> element:
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="120" slidingExpiration="true"/>
</authentication>
...
</system.web>
To get rid of your problem you should make sure that the session timeout is at least as long as the forms authentication timeout.
If you are allowing persisted cookies in forms authentication ("Remember me"), then there are no gurantees. In that case you just have to set the session timeout to "long enough" according to some criteria/specification.
Edit: Also check the settings on your application pool (under IIS) where the site is deployed. And specifically check what the "Idle Time-out" is. If this is set low (default value is 20 minutes I think), then IIS will shut down the application pool if no request have come in during that time. That (of course) terminates whatever in-proc sessions existed.
Forms Authentication stores its ticket in Cookie at client side or URL(if cookie is disabled).
Session variables are stored at server side with expired time. If you want your variable to be more persistent use cookie.
You can extend your session time out in web config. This is for 20 minutes.
<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
You said that you are working with ASP.NET Form authentication/authorization then I'd suggest you to use Profile instead of Session state.

Problem: control Session timeout

My session renews every 20 minutes. I've set timeout to 300 minutes but still it renews probably because Application Pool recycles.
I am storing UserId which is Guid in Session which returns null. Problem is when I use Membership using
Membership.GetUser().ProviderUserKey
it works fine. But obviously it makes a database call. How can I prevent this problem from happening? Why does Membership.GetUser().ProviderUserKey succeeds whereas Session doesn't?
In order to complete Jan's and Neil's answers, you should look at your web.config and set both timeouts (sessionState and authentication)
<sessionState timeout="300"/>
Sessionstate timeout specifies the number of minutes a session can be idle before it is abandoned. The default is 20.
<authentication mode="Forms">
<forms loginUrl="Login.aspx" timeout="300" />
</authentication>
Forms timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.
Your session may still be alive (if you set it to 300 minutes) but the ASP.NET membership could be expiring?
Have you increased the authentication timeout too?
<authentication mode="Forms">
<forms loginUrl="Login/" timeout="180"/>
</authentication>
You are mixing authentication and session. These are two completely different concepts.
GetUser() return the currently authenticated user form your MemberShipProvider.
Session and authentication have different timeouts - so its valid that your session times out but the user is still authenticated.

ASP.NET Session TimeOut problem

I have a wired scenario in one of my ASP.net application.
I am using ASP.net membership with my custom "roleManager",
and having below tag in web.config to restrict any user not having role of "Keywords"(roles) to access "Keywords"(path) folder
<location path="Keywords">
<system.web>
<authorization>
<allow roles="Keywords"/>
<deny users="*" />
</authorization>
</system.web>
</location>
If any user with some other role allow to assess this URL (Keywords in this case) will be redirected to a custom- Access denied page.
Now things working fine but when I left my application with a inactivity of 30 min I am not able to visit the "Keywords", all the time I end up with the custom- Access denied page, if I close the browser, login again it start working fine.
Please help me in this case.
Thanks in advance
ASP.NET sessions time out after 20 minutes by default, I think.
You can extend this by specifying a longer time (in minutes) in the Web.config:
<system.web>
<sessionState timeout="60"/>
...
</system.web>
If you are authenticating via Forms, you should raise the authentication cookie timeout value to match.
Also bear in mind that, when running the site under IIS, you should probably extend the application pool's idle timout to something similar. If you don't do this, the HttpApplication instance for your ASP.NET site will be unloaded, destroying any active sessions in the process.
Usually, the first and easiest thing to do is just change the configuration/system.web/sessionState#timeout value to something like “90″
<sessionState timeout="90" />
it still appears to be timing out after 20 minutes.
*This doesn’t make any sense, it explicitly says that the session timeout should be exactly 90 minutes.*
There’s a couple of issues that are tied together here:
The application pool’s worker process default idle timeout is also
set to 20 minutes
The default mode of storing session state is in the IIS process
The settings for the application pool can be found by clicking Properties (IIS 6) or Advanced Settings (IIS 7.5) on the application pool that the application is assigned to.
Ensure the value of "Idle-Time-out(minutes)" is set to the timeout of your session, at a minimum (ex 90), to ensure that all sessions persist for the entire session timeout period.
try this solution if still there is a problem refer to this article it tell more option to try
http://asp-net.vexedlogic.com/2012/05/23/aspasp-net-session-timeout-how-do-i-change-it/

Strange logging off on ASP.NET 3.5 website

Please help me I'm getting desperate here trying to find the problem, and I don't know where to start looking for it.
Here are the symptoms:
I've noticed, that when a user logs on in the morning, he is then immediately logged off, then when he logs on again, everything is fine and he can work on the site.
Every once in a while, when the user clicks a link, the page takes a lot of time to load, but it never actually loads, and the user is thrown to the login page.
Also, after an Exception has occurred in the website, the user is then thrown to the login page. It's as if the exception clears somehow the session.
Do any of you know of a situation where this might happen ?
The code I use in every page in my application is as follows :
If (Not User.Identity.IsAuthenticated) Then
Response.Redirect("../login2.aspx")
End If
' If session timeout then return to login screen '
If ((Session("LocationId") Is DBNull.Value) Or (Session("LocationId") Is Nothing))
Then
Response.Redirect("../login2.aspx")
End If
The code in the web.config:
<sessionState cookieless="false" timeout="600" />
<authentication mode="Forms">
<forms timeout="600" />
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
Why are you using that code in every page?
.NET authorization and authentication normally takes care of all those things if you have it set up correctly.
Related to this scenario *`
".... after an Exception has occurred
in the website, the user is then
thrown to the login page. It's as if
the exception clears somehow the
session
I know of one possible situation where it may occur.
It is far fetched especially in a production scenaio for multiple reasons but i have seen it happen :-)
If the session is In Memory and logging is done by writing to a log file that is in the Bin directory of the application, then this may occur as modifying the bin folder of the web application results in the application restarting i.e the in memory session getting lost.
Just one possible scenario. If your session is not in Memory OR your logging mechanism isnt like this, then this doesnt apply to you.
I am turning to all the dot net experts out there because I am really desperate,
let me give another symptom of the problem because it still persists,
the server is a very strong server - intel xeon with a 3 gb ram, so it is probably not a problem of resources.
When the user uses the system continuously there is no problem and she can work freely, the problem arises when the user leaves the computer (or the application for that matter) for as long as 5 minutes, then when she wants to continue working and clicks a link in the application she is thrown to the login page. when she tries to login again, she succeeds, but after she clicks another link, she is thrown out again, then when she logins she can work freely and everything is fine.
Somehow the session is being cleared when the site is idle. let me emphasize that this doesn't happen when I run the app in visual studio, only in iis.
The app was converted from asp.net 2.0 to 3.5,
that's it, thanks
First of all, you need to deny access for non-authenticated (anonymous) users:
<authorization>
<deny users="?" />
</authorization>
Have you configured default and login pages?
<authentication mode="Forms">
<forms name=".ASPXFORMSAUTH" loginUrl="Login.aspx" defaultUrl="Default.aspx" slidingExpiration="true" timeout="30" />
</authentication>
name sets the name of a cookie, useful if you will use .NET 2.0 built-in security infrastructure (roles, membership, etc)
slidingExpiration enabled normal timeout behavior - any user action resets timeout
If you are just using the normal session functionality in asp.net I believe that the session times out after 15-30 minutes of inactivity (I typically don't use session so I remember it is somewhere in this range). Every postback to the server resets this timer so if a user is active doing things then they won't hit this time out.
For the page taking a long time to load it is most likely due to the worker process recycling and that user is the first user to access the site after a recycle which triggers IIS to do all of it's compilation stuff and then serve the page which causes the delay. This only happens for the first visitor after a worker process recycle. You can change this behavior in IIS to happen on a schedule rather than after a certain amount of time has passed without activity. This will cause your worker process to take up more memory though so depending on your environment this might not be a good change to make.
EDIT: I should add that the code you posted explains exactly why the user is kicked back to the login page. It is checking to make sure that there is something in the session and if there isn't anything there it kicks the user back to the login page. So if they are inactive for too long your session times out, so it is cleared, and the user is kicked back to the login page by your code. Also you should use FormsAuthentication.RedirectToLoginPage(); for your redirect instead of Response.Redirect. This way after logging in they go back to the page they requested originally.

Resources