Session_End in Global.asax.cs not firing using forms authentication - c#

I have an asp.net 4.0 application that is using forms authentication set to a timeout at 45 minutes. I would like to redirect the user to a timeout page when the session has expired. Can anyone tell me how to do this? I am running .net 4.0.
web.config has:
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="~/Login.aspx"
defaultUrl="~/Default.aspx" protection="All" timeout="45"
requireSSL="false">
</forms>
</authentication>
Global.asax.cs file has:
void Session_End(object sender, EventArgs e)
{
Response.Redirect("~/Timeout.aspx");
}

It's not possible to do a redirect in the Session_End method. It's not running as a result of a request, so it doesn't have a Response object and there is no response to redirect anywhere.
It's not possible to do anything in the browser as a result of the session expiring. The HTTP protocol is request oriented, so there is no way to push a message from the server to the browser without the browser asking for it.
The browser just can't find out if the session has expired or not. If you would poll the server to check if the session has expired, it would keep the session alive, defeating the purpose of the timeout.
You can make a redirect after 45 minutes using just client script:
window.setTimeout(function() {
window.location.href = '/Timeout.aspx';
}, 1000*45*60);
However, this will make the redirect only based on the time since this browser window last contacted the server. If you have more than one browser window for the same session, it's possible that the session has actually not timed out.

How is your session state implemented? Session_End only works when you are using InProc.
See http://www.eggheadcafe.com/articles/20021016.asp

On MVC you can adding this code in _ViewStart.cshtml
_ViewStart.cshtml:
#{
Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5));
if(Session.IsNewSession)
Response.Redirect(“Logout.aspx");// or another page which you want.
}
How to Redirect on Session End

Related

MVC5 After Signout, Session and Cookies are cleared but still i can access mvc controller using old cookies by Postman [duplicate]

I have been banging my head against the wall and searching the web for this but I think I am having issues understanding the whole process of logging users out of an asp.net webforms application. The issue:
I am able to log in to my application and it uses cookies, so I have my cookie set in the browser.
here is the config forms authentication section,
<forms loginUrl="login.aspx" timeout="15" protection="All" name="Domain.MYDOMAIN" path="/" domain="mysite.local" cookieless="UseDeviceProfile"/>
here is the front end control
<li><asp:LoginStatus ID="LoginStatus1" runat="server" OnLoggedOut="OnLoggedOut" /></li>
In the OnLoggedOut Method we do something like this.
protected void OnLoggedOut(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
/* Abandon session object to destroy all session variables */
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
Response.Redirect("~/login.aspx");
}
This will clear the cookies from the browser. But if before I do this I copy the cookie name pair value of Domain.MYDOMAIN = "what ever it would be"
and add that to a postman call, it is still showing me as logged in! Very frustrating.
when I am logged in
I log out using the logout button mentioned above and the cookie is removed
Then I take that cookie to Postman and make the call to the landing / default page and it is showing me as logged in still!!!
I have been reading that the cookie is related to a "ticket" but I am not sure how to expire that ticket on the server side. Once the user clicks logout I dont want this cookie value to be used again to reach a page, any page within the application. Any help would be appreciated! Thank You!
Side Note: I have my session state set to InProc
<sessionState mode="InProc" />
Ones the user is authenticate with user name and password, then we set a cookie that have a time out and this cookie let him login.
Even if you delete the cookie from one browser, if you still have it and place it again – you permit to login again because the cookie is gives the “OK” to do that.
This is not only on asp.net but everywhere (Microsoft, google, Facebook).
To add an extra layer of security, and avoid to someone steal the cookie:
First step is to force only the SSL for the cookies (*). <httpCookies httpOnlyCookies="true" requireSSL="true" />. Using that you make it difficult to impossible to steal the cookie
Second step is on logout to save that cookie on a database, then on every request check if the cookies have been logged out
Third step is to also check if the cookie come from the same browser id.
So, you connect the cookie with the browser data, and with a flag that the user press the logout.
You make that checks on global.asax
protected void Application_BeginRequest(Object sender, EventArgs e)
(*) The first step : Can some hacker steal a web browser cookie from a user and login with that name on a web site?
The difficult way is to add the database extra layer of protection and connect the cookie with other user information's as I say, the browser id, and a flag if have been logged out. The main idea is to keep on server the authenticated cookie that you have set and double check it - now you don't do that.

How to check reset session

In my application session is not reset if the user is active.
My session timeout time is 20min.
means: Let an user logged in to my application and doing some operation. That operation took 20 mins. then in the middle of the operation application showing session time out error and redirect to login page which in not good.
how to solve this problem.
How to reset the session when the user is active. If the user is inactive for 20 min then it should redirect to login page.
If the user is ideal for 15 min and after that user do some operation then the user should not redirect to login page.
I found some link to set from IIS label which is not working.
can you please help to solve this one.
Thanks in advance
if you are using forms authentication then following code will help.
<authentication mode="Forms">
<forms defaultUrl="FrmAbc.aspx" loginUrl="FrmLogin.aspx" protection="All" cookieless="UseCookies" slidingExpiration="true" timeout="1200" />
</authentication>

Session time out Logout Url ASP.Net

I have an issue with my ASP.Net web app built in 4.0 framework.
I have the below set in the web config -
<authentication mode="Forms">
<forms loginUrl="~/SignIn.aspx" protection="All" timeout="2880" path="/" />
</authentication>
when a user clicks my url he sees the login page.
Now the session timeout is set to the default session time out from IIS which is 20 minutes.
Now when the session expires I would like to force the user to redirect to Logout.aspx
How can I achieve this? I would like to redirect the user to Logout.aspx page once the session times out.
The short answer is to check HttpContext.Current.Session.IsNewSession on each page request to see if the user's session timed out and has started a new session. In the event that it is a new session, redirect the user to the page of your choosing.
If you're using MVC or even just want to see a more thorough explanation of session timeouts in action, check out http://tyronedavisjr.com/2008/11/23/detecting-session-timeouts-using-a-aspnet-mvc-action-filter/ for an example.

Determine when an ASP.NET Forms Authentication will expire

Is it possible to determine the date & time when an ASP.NET session will expire when using Forms Authentication?
I would like to warn users when their sessions are about to expire. There is no session state & sliding expiration is disabled. Here are some of the system.web settings:
<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="Login.aspx" requireSSL="false" enableCrossAppRedirects="true" cookieless="AutoDetect" timeout="2" slidingExpiration="false"/>
</authentication>
<sessionState mode="Off"/>
The timeout / lifetime of a session is easy to determine, but should the user refresh the page within the session windows, adding the lifetime value to the date-time at reload will not be accurate.
Using an authentication cookie with FormsAuthenticationTicket ticket encrypted as its value, one can decrypt it to get the expiration date-time.
Although some AJAX calls may be made, the user might interact with the UI without any post back or request to the webserver.
Any ideas on how I can achieve this type of behavior without the use of cookies?
I have a similar problem. In my case given the low number of users, im opting for a better user experience with a polling ajax call on the page to call back into the server and check the expiration ticket. You may be able to get away with tweaking the below code and including expiration info in the page via http and keeping track of time in client javascript if you dont want to go the ajax route.
if (User.Identity.IsAuthenticated)
{
var identity = (FormsIdentity)User.Identity;
viewModel.UtcInactivityExpiryDate = identity.Ticket.Expiration.ToUniversalTime();
}
If you go the ajax route, there is another gotcha. You have to stop the ajax call itself from renewing the inactivity timeout if you are using one. You can do that by overwriting the new authentication cookie with the original one. at the end of your ajax request.
var requestCookie = HttpContext.Current.Request.Cookies[".ASPXAUTH"];
if (requestCookie != null)
{
HttpContext.Current.Response.Cookies.Add(requestCookie);
}

Issue with cleaning browser cache and cookies on logout in ASP.NET MVC 3

It's quite common topic I think, but I can't resolve my problem. In my application build with ASP.NET MVC 3, I'm using form authentication along with output caching:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" name=".CMS" protection="All" timeout="43200" cookieless="UseCookies"/>
</authentication>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="Dynamic" duration="3600" location="Client" varyByParam="id" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
My LogOff action looks folowing:
public ActionResult LogOff()
{
_formsService.SignOut();
return RedirectToAction("Index", "Dynamic");
}
this action uses simple SignOut method:
public void SignOut()
{
FormsAuthentication.SignOut();
HttpContext.Current.Session.Abandon();
// clean auth cookie
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, string.Empty);
authCookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(authCookie);
// clean session cookie
HttpCookie sessionCookie = new HttpCookie("ASP.NET_SessionId", string.Empty);
sessionCookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(sessionCookie);
}
But problem is following:
the page http://localhost/app/dynamic/page is protected. I cannot enter this page untill I login. After login, I have access for browsing such page. After logout, and then entering the page again, unfortunately I can still view its content.
How to prevent access to protected pages after logout, when caching is enabled and I was previously visiting such pages ? What I'm doing wrong ? The cookies should be cleaned in another way ?
Regards
The page is still cached. You need to add the following response header:
cache-control : no-cache
which doesn't actually prevent caching.
The cache-control response header's no-cache directive means that the browser
MUST NOT use the response to satisfy a subsequent request without successful revalidation
with the origin server.
If you really want to prevent caching, specify the no-store directive. That tells the browser that it
MUST NOT store any part of either this response or the request that elicited it. This
directive applies to both non-shared and shared caches. "MUST NOT store" in this context
means that the cache MUST NOT intentionally store the information in non-volatile
storage, and MUST make a best-effort attempt to remove the information from volatile
storage as promptly as possible after forwarding it.
See the HTTP 1.1 specs for details on cache-control and its directives.
Take a look at this post Asp.Net Mvc Can Not Log Out . I believe it should provide the code snippet needed to logout and clear cache.
You can't clear then browser cache from the server.
IMO the only right thing to do is invalidating the cookie on the server side(i.e. even if somebody gets to know the cookie he can't use it anymore), and optionally deleting the cookie on the client.
Just deleting the cookie isn't enough IMO.
Have you veriifed that browser actually makes request to the page http://localhost/app/dynamic/page (i.e. using Fiddler)?
If page is served from browser's cahce you need to set cache control header on that app/dynamic/page so browser is forced to query the page from server.
If page is retrived from server than see if cookies are still there (your cookie code looks ok, but still something could be wrong) OR if server side caching kicks in.

Categories

Resources