Session management in Visual Studio 2013? - asp.net

Im new developer in asp.net. I want to make a Session management that if 10 minutes passes without any action, the system will end the session and logout the user.
I searched about it and I found this code:
In Web.config file:
<sessionState
mode="InProc"
cookieless="true"
timeout="10" />
And in the page we want to end the session:
public int Timeout { get; set; }
But when I tried it, it didn't work!
I don't not know should I try it in a server rather than localhost or this code does not satisfy the purpose that I need ?

try
public class PageBase : System.Web.UI.Page
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
AutoRedirect();
}
public void AutoRedirect()
{
int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000);
string str_Script = #"
<script type='text/javascript'>
intervalset = window.setInterval('Redirect()'," + int_MilliSecondsTimeOut.ToString() + #");
function Redirect()
{
alert('Your session has been expired and system redirects to login page now.!\n\n');
window.location.href='/login.aspx';
}
</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", str_Script);
}
}
Read more How to do auto logout and redirect to login page when session expires using asp.net?
Auto redirect to login page when Session is expired

Try this in page load
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Clear();
Authentication.SignOut();
Response.Redirect("~/Login.aspx");

Related

Execute some code for each request for ASP.NET (aspx and cshtml )

Is there a way to write some code that would be executed for each request to a .aspx or a .cshtml page in asp.net 4.5 apart from using a base page class. it is a very huge project and making changes to all pages to use a base page is a nightmare. Also i am not sure how would this be done for a cshtml page since they don't have a class.
Can we use the Application_BeginRequest and target only the aspx and cshtml files since the website is running in integrated mode.?
basically, i have to check if a user who is accessing the website has a specific ip address against a database and if yes then allow access otherwise redirect.
we are using IIS8 and ASP.Net 4.5 and ASP.Net Razor Web Pages
Also i am not sure how would this be done for a cshtml page since they don't have a class.
You could place a _ViewStart.cshtml file whose contents will get executed on each request.
Alternatively you could write a custom Http Module:
public class MyModule: IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(OnBeginRequest);
}
public void Dispose()
{
}
public void OnBeginRequest(object s, EventArgs e)
{
// this code here's gonna get executed on each request
}
}
and then simply register this module in your web.config:
<system.webServer>
<modules>
<add name="MyModule" type="SomeNamespace.MyModule, SomeAssembly" />
</modules>
...
</system.webServer>
or if you are running in Classic Mode:
<system.web>
<httpModules>
<add name="MyModule" type="SomeNamespace.MyModule, SomeAssembly" />
</httpModules>
</system.web>
basically, i have to check if a user who is accessing the website has
a specific ip address against a database and if yes then allow access
otherwise redirect.
Inside the OnBeginRequest method you could get the current user IP:
public void OnBeginRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
var request = app.Context.Request;
string ip = request.UserHostAddress;
// do your checks against the database
}
Asp.net MVC filters are especially designed for that purpose.
You would implement ActionFilterAttribute like this (maybe put this new class in a Filters folder in your webapp solution):
public class IpFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string ip = filterContext.HttpContext.Request.UserHostAddress;
if(!testIp(ip))
{
if (true /* You want to use a route name*/)
filterContext.Result = new RedirectToRouteResult("badIpRouteName");
else /* you want an url */
filterContext.Result = new RedirectResult("~/badIpController/badIpAction");
}
base.OnActionExecuting(filterContext);
}
private bool testIp(string inputIp)
{
return true /* do you ip test here */;
}
}
Then you have to decorate any action that would perform the ipcheck with IpFilter like so :
[IpFilter]
public ActionResult AnyActionWhichNeedsGoodIp()
{
/* do stuff */
}

How to redirect to logon page when session State time out is completed in asp.net mvc

I have an ASP.NET MVC4 application where I am implementing sessionTimeout like:
<configuration>
<system.web>
<sessionState timeout="2"></sessionState>
</system.web>
</configuration>
And in authentication:
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="1" />
</authentication>
</system.web>
</configuration>
After the session has expired (2 mins), I need to redirect to the logon page, but the redirection doesn't occur.
How can I change the code so that it will redirect?
One way is that
In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.
But this is very hectic method
To over come this you need to create your own ActionFilterAttribute which will do this, you just need to add this attribute in every action method.
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute like so:
[SessionExpire]
public ActionResult Index()
{
return Index();
}
This will do you work.
I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.
In short, I catch session end in _Layout 1 minute before and make redirection.
I try to explain everything step by step.
If we want to session end 30 minute after and redirect to loginPage see this steps:
Change the web config like this (set 31 minute):
<system.web>
<sessionState timeout="31"></sessionState>
</system.web>
Add this JavaScript in _Layout (when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)
<script>
//session end
var sessionTimeoutWarning = #Session.Timeout- 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location = "/Account/LogOff";
}
</script>
Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page
public ActionResult LogOff()
{
Session["User"] = null; //it's my session variable
Session.Clear();
Session.Abandon();
FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
return RedirectToAction("Login", "Account");
}
I hope this is a very useful code for you.
There is a generic solution:
Lets say you have a controller named Admin where you put content for authorized users.
Then, you can override the Initialize or OnAuthorization methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:
protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
//lets say you set session value to a positive integer
AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
if (AdminLoginType == 0)
{
filterContext.HttpContext.Response.Redirect("~/login");
}
base.OnAuthorization(filterContext);
}

.Net web application behind a WebSeal reverse proxy

We are currently designing a solution that will run as a .Net Web application behind a WebSeal reverse proxy.
I have seen some comments on the net where people have had various problems with this, for example rewriting of viewstate.
Question is: Has anyone implemented this combination of techologies and got it to work?
I made an ASP.NET application workin behind WEBSEAL. After lot of study and development and test it works.
I suggest some issues to help you:
IIS and ASP.NET are case insensitive
("...Login.aspx" and "...login.aspx" both lead to the same page); by default webseal is case sensitive. So you should set WEBSEAL junction to be case insensitive or check any single link (page, javascript, image)
Internal links, written as server relative URLs won't be served
WEBSEAL changes any link referring your application but doesn't change links to other applications.
Internal links, written as server relative URLs instead of application relative URLs won't be changed (WEBSEAL doesn't recognize it's the same application) and won't be served (WEBSEAL rejects links that are not modified).
First rule is to check any single link and make it an application relative URL .
Look at rendered HTML if you find <.. href=/ anything> : this i a server relative URL and it is bad.
Look in the Code Behind if you use "= ~/ anything" it is good. If you use "= / anything" OR ResolveUrl(..) it is bad.
But this is not enough: AJAX puts loads of javascript and code inside ScriptResource.axd and WebResource.axd and creates server relative URL to link it. This links are not controlled by programmers and there is no easy way to change them.
Easy solution (if possible): solve the problem setting WEBSEAL junction to be transparent.
Hard solution: write the following code (thanks to this answer)
protected void Page_Load(object sender, EventArgs e)
{
//Initialises my dirty hack to remove the leading slash from all web reference files.
Response.Filter = new WebResourceResponseFilter(Response.Filter);
}
public class WebResourceResponseFilter : Stream
{
private Stream baseStream;
public WebResourceResponseFilter(Stream responseStream)
{
if (responseStream == null)
throw new ArgumentNullException("ResponseStream");
baseStream = responseStream;
}
public override bool CanRead
{ get { return baseStream.CanRead; } }
public override bool CanSeek
{ get { return baseStream.CanSeek; } }
public override bool CanWrite
{ get { return baseStream.CanWrite; } }
public override void Flush()
{ baseStream.Flush(); }
public override long Length
{ get { return baseStream.Length; } }
public override long Position
{
get { return baseStream.Position; }
set { baseStream.Position = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{ return baseStream.Read(buffer, offset, count); }
public override long Seek(long offset, System.IO.SeekOrigin origin)
{ return baseStream.Seek(offset, origin); }
public override void SetLength(long value)
{ baseStream.SetLength(value); }
public override void Write(byte[] buffer, int offset, int count)
{
//Get text from response stream.
string originalText = System.Text.Encoding.UTF8.GetString(buffer, offset, count);
//Alter the text.
originalText = originalText.Replace(HttpContext.Current.Request.ApplicationPath + "/WebResource.axd",
VirtualPathUtility.MakeRelative(HttpContext.Current.Request.Url.AbsolutePath, "~/WebResource.axd"));
originalText = originalText.Replace(HttpContext.Current.Request.ApplicationPath + "/ScriptResource.axd",
VirtualPathUtility.MakeRelative(HttpContext.Current.Request.Url.AbsolutePath, "~/ScriptResource.axd"));
//Write the altered text to the response stream.
buffer = System.Text.Encoding.UTF8.GetBytes(originalText);
this.baseStream.Write(buffer, 0, buffer.Length);
}
This intercepts the stream to the page and replaces all occurrences of "/WebResource.axd" or "ScriptResource.axd" with "../../WebResource.axd" and "../../ScriptResource.axd"
Develop code to get actual WEBSEAL user
WEBSEAL has been configured to put username inside HTTP_IV_USER. I created Webseal\Login.aspx form to read it programmatically.
Now, in order to make this user the CurrentUser I put an hidden asp.Login
<span style="visibility:hidden">
<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Default.aspx">..
and clicked the button programmatically
protected void Page_Load(object sender, EventArgs e)
{
string username = Request.ServerVariables["HTTP_IV_USER"];
(Login1.FindControl("Password") as TextBox).Text = MyCustomProvider.PswJump;
if (!string.IsNullOrEmpty(username))
{
(Login1.FindControl("UserName") as TextBox).Text = username;
Button btn = Login1.FindControl("LoginButton") as Button;
((IPostBackEventHandler)btn).RaisePostBackEvent(null);
}
else
{
lblError.Text = "Login error.";
}
}
When LoginButton fires, application reads UserName (set from WEBSEAL variable) and password (hard coded). So i implemented a custom membership provider that validates users and sets current Principal.
Changes in web.config
loginUrl is the URL for the login page that the FormsAuthentication class will redirect to. It has been set to WEBSEAL portal: not authenticated user and logout button will redirect to portal.
<authentication mode="Forms">
<forms loginUrl="https://my.webseal.portal/" defaultUrl="default.aspx"...."/>
</authentication>
Since Webseal/login.aspx is NOT default login page, authorization tag grants access to not authenticated users:
<location path="Webseal/login.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
Application is set to use custom membership providers:
<membership defaultProvider="MyCustomMembershipProvider">
<providers>
<add name="MyCustomMembershipProvider" type="MyNamespace.MyCustomMembershipProvider" connectionStringName="LocalSqlServer"/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="MyCustomRoleProvider">
<providers>
<add name="MyCustomRoleProvider" type="MyNamespace.MyCustomRoleProvider" connectionStringName="LocalSqlServer"/>
</providers>
</roleManager>
Debug is set to off:
<compilation debug="false" targetFramework="4.0">
that's all folks!
I initially has some issues with the ASP.Net app when accessed through WebSeal. I was running the site on a development server. What worked for me was to deploy the application with debugging turned off in the config file.
<compilation debug="false" ...>
With debugging turned on, there were some AJAX calls that would work fine when I accessed the site directly but would fail when access through WebSeal. Once I turned the debugging off, everything work fine.
Also, because WebSeal requires anonymous authentication, we couldn't have used Windows Authentication.

ASP.NET SSL - issue is the postback, so OnInit etc won't work

When should I enforce SSL for secure pages in an ASP.NET page life-cycle?
I mean should I do it inside page_load? or OnInit? or some other function?
I am using the following code to enforce SSL for certain pages, but where should I put this code? Earlier I placed it inside OnInit function, but that did not work well with ASP.NET wizards. Do I need to check whether it's postback or not first?
If postback drops https, shouldn't my code enforce it? If postback does not drop https, shouldn't my code stop redirecting and move to the next step of the wizard? It seems like it keeps redirecting.
if (!HttpContext.Current.Request.IsSecureConnection) {
HttpContext.Current.Response.Redirect(SiteNavigation.ResolveAbsoluteUrl(true, HttpContext.Current.Request.Url.PathAndQuery));
}
You have basically two options.
If you want all authenticated pages to run under SSL, you can set the requireSSL="true" attribute on forms authentication. Just make sure your login page is also running on HTTPS.
You can also set this on a page-by-page basis. I found this works well in a "page base" class that inherits from System.Web.UI.Page, and that all your pages inherit from (instead of System.Web.UI.Page).
public class PageBase : System.Web.UI.Page
{
public bool RequiresSSL {get; set;}
string currentPage = Request.Url.ToString();
public PageBase()
{
Init += new EventHandler(PageBase_Init);
}
void PageBase_Init(object sender, EventArgs e)
{
if ((RequiresSSL) && (WebConfigurationManager.AppSettings["SSLavailable"] == "true"))
{
if (currentPage.ToLower().StartsWith("http://"))
{
redirectTo = "https://" + currentPage.Substring(7);
Response.Redirect(redirectTo);
}
}
else
{
if (currentPage.ToLower().StartsWith("https://"))
{
redirectTo = "http://" + currentPage.Substring(8);
Response.Redirect(redirectTo);
}
}
}
}
The AppSettings value of SSLavailable allows you to switch the whole mechanism off when you're running in test mode without SSL.
For pages that need to run in SSL mode, all they need to do is set RequiresSSL:
public partial class ChangePassword : PageBase
{
public ChangePassword()
{
PreInit += new EventHandler(ChangePassword_PreInit);
}
void ChangePassword_PreInit(object sender, EventArgs e)
{
RequiresSSL = true;
}
}
It works, very smoothly, and any other pages they go to after the secure page will automatically switch back to HTTP protocol.
I usually do this in the OnPreLoad event to force SSL:
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
String qs;
qs = Request.QueryString;
//// Force the page to be opened under SSL
if (!Request.IsSecureConnection)
{
if (qs != "")
{
qs = "?" + qs;
}
Response.Redirect("https://" +
Request.ServerVariables["SERVER_NAME"].ToString() +
Request.ServerVariables["PATH_INFO"].ToString() + qs);
}
}
If you want to force SSL for all pages, it may be a good fit for an HttpModule. I have come up with the following:
using System;
using System.Web;
namespace CustomHttpModules
{
public class EnforceSSLModule : IHttpModule
{
public void Init(HttpApplication httpApp)
{
httpApp.PreRequestHandlerExecute += this.OnPreRequestHandlerExecute;
}
public void Dispose()
{
}
public void OnPreRequestHandlerExecute(object o, EventArgs e)
{
using (HttpApplication httpApp = (HttpApplication)o)
{
if (HttpContext.Current != null)
{
HttpContext ctx = HttpContext.Current;
String qs;
qs = ctx.Request.QueryString;
//// Force the page to be opened under SSL
if (ctx.Request.IsSecureConnection)
{
if (qs != "")
qs = "?" + qs;
ctx.Response.Redirect("https://" +
ctx.Request.ServerVariables["SERVER_NAME"].ToString() +
ctx.Request.ServerVariables["PATH_INFO"].ToString() + qs);
}
}
}
}
}
}
To use the HttpModule in IIS5.1 or IIS6, drop the compiled assembly for the HttpModule in your site's bin folder and add the following to your web.config's HttpModules section:
<add type="CustomHttpModules.EnforceSSLModule, dllname" name="EnforceSSLModule" />
(where dllname is the name of your assembly file without the extension)

ASP.NET Push Redirect on Session Timeout

I'm looking for a tutorial, blog entry, or some help on the technique behind websites that automatically push users (ie without a postback) when the session expires. Any help is appreciated
Usually, you set the session timeout, and you can additionally add a page header to automatically redirect the current page to a page where you clear the session right before the session timeout.
From http://aspalliance.com/1621_Implementing_a_Session_Timeout_Page_in_ASPNET.2
namespace SessionExpirePage
{
public partial class Secure : System.Web.UI.MasterPage
{
public int SessionLengthMinutes
{
get { return Session.Timeout; }
}
public string SessionExpireDestinationUrl
{
get { return "/SessionExpired.aspx"; }
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.PageHead.Controls.Add(new LiteralControl(
String.Format("<meta http-equiv='refresh' content='{0};url={1}'>",
SessionLengthMinutes*60, SessionExpireDestinationUrl)));
}
}
}
The SessionExpireDestinationUrl should link to a page where you clear the session and any other user data.
When the refresh header expires, it will automatically redirect them to that page.
You can't really "push" a client from your website. Your site will respond to requests from the client, but that's really it.
What this means is that you need to write something client-side (Javascript) that will determine when the user has timed out, probably by comparing the current time with the most recent time they have in a site cookie (which you update with the current time each time the user visits a page on your site), and then redirect if the difference is greater than a certain amount.
(I note that some people are advocating just creating a script that will forward the user after a certain amount of time on a page. This will work in the simple case, but if the user has two windows open on the site, and is using one window a lot, and the other window not-so-much, the not-so-much one will suddenly redirect the user to the forwarding page, even though the user has been on the site constantly. Additionally, it's not really in sync with any session keeping you're doing on the server side. On the other hand, it's certainly easier to code, and if that's good enough, then great!)
In the <HEAD> section, use a META refresh tag like this:
<meta http-equiv="refresh" content="0000; URL=target_page.html">
where 0000 is your session timeout in seconds, and target_page.html the address of the page to be redirected to.
Using Custom Page class and Javascript also we can achieve it.
Create a custom pagebase class and write the common functionality codes into this class. Through this class, we can share the common functions to other web pages. In this class we need inherit the System.Web.UI.Page class. Place the below code into Pagebase class
PageBase.cs
namespace AutoRedirect
{
public class PageBase : System.Web.UI.Page
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
AutoRedirect();
}
public void AutoRedirect()
{
int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000);
string str_Script = #"
<script type='text/javascript'>
intervalset = window.setInterval('Redirect()'," +
int_MilliSecondsTimeOut.ToString() + #");
function Redirect()
{
window.location.href='/login.aspx';
}
</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", str_Script);
}
}
}
Above AutoRedirect function will be used to redirect the login page when session expires, by using javascript window.setInterval, This window.setInterval executes a javascript function repeatedly with specific time delay. Here we are configuring the time delay as session timeout value. Once it’s reached the session expiration time then automatically executes the Redirect function and control transfer to login page.
OriginalPage.aspx.cs
namespace appStore
{
public partial class OriginalPage: Basepage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
OriginalPage.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="OriginalPage.aspx.cs" Inherits="AutoRedirect.OriginalPage" %>
Web.config
<system.web>
<sessionState mode="InProc" timeout="3"></sessionState>
</system.web>
Note:
The advantage of using Javascript is you could show custom message in alert box before location.href which will make perfect sense to user.
In case if you don't want to use Javascript you could choose meta redirection also
public void AutoRedirect()
{
this.Header.Controls.Add(new LiteralControl(
String.Format("<meta http-equiv='refresh' content='{0};url={1}'>",
this.Session.Timeout * 60, "login.aspx")));
}
Just copy and paste this code snippet in your Web.Config file :
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" slidingExpiration="true" timeout="29" />
</authentication>
<sessionState timeout="30" mode="InProc" cookieless="false" />
You can put this line to your Site.Master :
Response.AppendHeader("Refresh",
Convert.ToString((Session.Timeout * 60)) +
";URL=~/Login.aspx");
I'm using MVC3 ASp.net as beginner, I tried many solution to solve my session problem ( since i'm using Session variable in my code, and after timeout i didn't have session values while i'm keep using it And I just find that my problem was in config file. the timeout between Authentication and sessionState should be so close. so they Killed (empty) at the same time // add timeout 1 and 2 for testing.. it's should be at least 29 and 30
I used others way it's work too :
Starting from :
protected void Session_Start(object src, EventArgs e)
{
if (Context.Session != null)
{
if (Context.Session.IsNewSession)//|| Context.Session.Count==0)
{
string sCookieHeader = Request.Headers["Cookie"];
if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
//if (Request.IsAuthenticated)
FormsAuthentication.SignOut();
Response.Redirect("/Account/LogOn");
}
}
}
}
protected void Session_End(object sender, EventArgs e)
{
//Code that runs when a session ends.
//Note: The Session_End event is raised only when the sessionstate mode
//is set to InProc in the Web.config file. If session mode is set to StateServer
//or SQLServer, the event is not raised.
Session.Clear();
}
And :
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
if (ctx.Session != null)
{
// check if a new session id was generated
if (ctx.Session.IsNewSession)
{
// If it says it is a new session, but an existing cookie exists, then it must
// have timed out
string sessionCookie = ctx.Request.Headers["Cookie"];
if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
{
ctx.Response.Redirect("~/Home/LogOn");
}
}
}
base.OnActionExecuting(filterContext);
}
}
And even worked with Ajax to solve session issuse:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Session.Count == 0 || Session["CouncilID"] == null)
Response.Redirect("/Account/LogOn");
if (Request.IsAjaxRequest() && (!Request.IsAuthenticated || User == null))
{
filterContext.RequestContext.HttpContext.Response.StatusCode = 401;
}
else
{
base.OnActionExecuting(filterContext);
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeUserAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsAjaxRequest())
{//validate http request.
if (!httpContext.Request.IsAuthenticated
|| httpContext.Session["User"] == null)
{
FormsAuthentication.SignOut();
httpContext.Response.Redirect("~/?returnurl=" + httpContext.Request.Url.ToString());
return false;
}
}
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult
{
Data = new
{
// put whatever data you want which will be sent
// to the client
message = "sorry, but you were logged out"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
Unfortunately it can't be done. The session timeout only occurs on the server side and you won't detect this until the user performs some kind of post back action.
However, what you CAN do is to inject some HTML or JavaScript header code that will automatically push the user to a logout page in the same timeframe as your session timeout. This doesn't guarantee a perfect synch, and you may run into issues if your user is doing some time intensive items and you are not resetting the clock.
I typically add this code to my Page_Load events to accomplish this.
' Register Javascript timeout event to redirect to the login page after inactivity
Page.ClientScript.RegisterStartupScript(Me.GetType, "TimeoutScript", _
"setTimeout(""top.location.href = 'Login.aspx'""," & _
ConfigurationManager.AppSettings("SessionTimeoutMilliseconds") & ");", True)
And if you use the following Logon controller, it will send you to the requested URL before logon:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
//return Redirect(returnUrl);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Of course you need to use [Authorize] over controller class or even Action in specific.
[Authorize]
public class MailController : Controller
{
}
Well this gets tricky for AJAX requests as Zhaph - Ben Duguid pointed out. Here was my solution to make this work with AJAX (using Telerik web controls but they are built using ASP.NET AJAX toolkit I believe).
In a nutshell, I rolled my own sliding expiration session type thing.
In my Site.Master, I am updating a session variable on EVERY postback (postback or AJAX request because AJAX requests still kick off the Page_Load event):
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (this.Request.IsAuthenticated)
this.pnlSessionKeepAlive.Visible = true;
else
this.pnlSessionKeepAlive.Visible = false;
}
if (this.Session["SessionStartDateTime"] != null)
this.Session["SessionStartDateTime"] = DateTime.Now;
else
this.Session.Add("SessionStartDateTime", DateTime.Now);
}
Then in my markup for my site.master, I included an iframe with a ASPX page I use "behind the scenes" to check and see if my custom sliding expiration has expired:
<asp:Panel runat="server" ID="pnlSessionKeepAlive" Visible="false">
<iframe id="frame1" runat="server" src="../SessionExpire.aspx" frameborder="0" width="0" height="0" / >
</asp:Panel>
Now in my SessionExpire.aspx page, I just refresh the page every so often and check if the timestamp has lapsed and if so, I redirect to my logout.aspx page that then determines which login page to send the user back to:
public partial class SessionExpire : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
/* We have to do all of this because we need to redirect to 2 different login pages. The default .NET
* implementation does not allow us to specify which page to redirect expired sessions, its a fixed value.
*/
if (this.Session["SessionStartDateTime"] != null)
{
DateTime StartTime = new DateTime();
bool IsValid = DateTime.TryParse(this.Session["SessionStartDateTime"].ToString(), out StartTime);
if (IsValid)
{
int MaxSessionTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["SessionKeepAliveMins"]);
IsValid = (DateTime.Now.Subtract(StartTime).TotalMinutes < MaxSessionTimeout);
}
// either their session expired or their sliding session timeout has expired. Now log them out and redirect to the correct
// login page.
if (!IsValid)
this.Logout();
}
else
this.Logout();
// check every 60 seconds to see if the session has expired yet.
Response.AddHeader("Refresh", Convert.ToString(60));
}
private void Logout()
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "TimeoutScript",
"setTimeout(\"top.location.href = '../Public/Logout.aspx'\",\"1000\");", true);
}
}
Many thanks to the people above who posted info, this lead me to my solution and hope it helps others.

Resources