Here's what has worked for me on recent projects.
First, in a global js file I setup the following:
$.ajaxSetup({
error: function (xhr, textStatus, errorThrown) {
//make sure this isn't caused by navigating away from the page by checking the xhr readyState
if (xhr.readyState == 4) {
switch (xhr.status) {
case 401:
case 403:
// take them to the login but hang on to their current url
//calling reload does this by leveraging the rest of our framework automagically!
window.location.reload(true);
break;
default:
bootbox.alert('<div class="text-center"><h2>An error was encountered</h2><h3>Sorry, an error has occurred. The system administrators have been notified.</h3></div>');
break;
}
}
}
});
Obviously a full page reload already handles booting the user back to login, so I just detect a 403 and force the page to reload. There's also some other ajax error handling there, not necessary for what you're requesting.
Now, that 403 isn't the default unauth status, so to make that happen I have a custom auth attribute:
public class AuthorizationRequiredAttribute : AuthorizeAttribute
{
#region Overrides of AuthorizeAttribute
public override void OnAuthorization(AuthorizationContext filterContext)
{
var skipAuthorization =
filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
if (skipAuthorization) return;
base.OnAuthorization(filterContext);
//now look to see if this is an ajax request, and if so, we'll return a custom status code
if (filterContext.Result == null) return;
if (filterContext.Result.GetType() == typeof (HttpUnauthorizedResult) &&
filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new ContentResult();
filterContext.HttpContext.Response.StatusCode = 403;
}
}
#endregion
}
There are reasons (that I can't recall now, but pretty sure I got the info from somewhere else on SO) that you can't rely on the standard unauth status code and thus must override it with that 403. Hope this helps!