2

In my MVC3 application there are a couple of situations where I a display a splash screen dynamically load a partial view via jQuery's ajax methods and injecting html into the DOM.

The thing is if authentication expires and then a user initiates an ajax call, the action being called redirects to the log in page, so the html for the log in page is returned and is injected into the DOM, which is obviously going to be extremely confusing for the user.

How do people normally deal with this situation? I imagine it is common as forms auth and ajax requests for html are something that I do a lot.

Chris
  • 3,191
  • 4
  • 22
  • 37
jcvandan
  • 14,124
  • 18
  • 66
  • 103

1 Answers1

2

Here is an AuthorizeAjax action filter I wrote for exactly this situation, you can use it as follows:

[AuthorizeAjax]
public ActionResult GetNewData()
{
    //controller logic here
}

By adding the below to your project all you need is a partial view called "AjaxAccessError" in your shared folder, personally, I return a link to the real logon page :)

Hope this helps!

namespace System.Web.Mvc
{
    public class AuthorizeAjaxAttribute : AuthorizeAttribute
    {
        private bool _failedAuthorisation;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                _failedAuthorisation = true;
                return false;
            }
            else
            {
                String[] RoleArray = Roles.Split(',');
                foreach (var r in RoleArray)
                {
                    if (httpContext.User.IsInRole(r))
                    {
                        _failedAuthorisation = false;
                        return true;
                    }
                }

                _failedAuthorisation = true;
                return false;
            }
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (_failedAuthorisation)
            {
                filterContext.Result = new PartialViewResult { ViewName = "AjaxAccessError" };
            }
        }
    }
}
Chris
  • 3,191
  • 4
  • 22
  • 37