MVC filter action redirect to infinite loop

1.2k views Asked by At

I'm trying to create filter, the filter supposed to check role (not asp .NET membership or Identity but my-self one) and my wish is to restrict all controller actions (let call it "AuthController" for the following) from low-role level users.

In my filter condition i remove the restrict user to home page.

The problem occur when i remove the high-role level in Ajax within the AuthController Then my partial view get me to the home page.

is there an elegant way to avoid that?

    [HttpPost, ActionName("DeleteRole")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(Guid UserId, Guid RoleId)
    {
        CustomProvider CP = new CustomProvider();
        CP.DeleteRoleFromUser(UserId, RoleId);

        return PartialView("RolesDelete", db.Role.Where(p => p.Id == RoleId).SingleOrDefault());

    }

The filter:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (filterContext.HttpContext.User.Identity.IsAuthenticated && string.IsNullOrEmpty(NameFromExternal))
        {
            NameFromExternal = filterContext.HttpContext.User.Identity.Name;
        }
        CustomProvider cp = new CustomProvider();
        if (CustomRoleProvider.Instance.IsUserInRole(cp.getADNameFromFullDomainName(NameFromExternal), eRoles.High.ToString()))
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Auth" }, { "action", "Index" } });
            filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
        }
        else
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" } });
            filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
        }

    }
2

There are 2 answers

0
shdr On BEST ANSWER

At the filter let the unauthrized user to some controller action that refer hot to Home page, and in the partial view set redirection statement that will appear on as a partial page he restricted.

Controller:

public ActionResult Redirection(string controller, string view)
    {
        ViewBag.TargetCtrl = "Home";
        ViewBag.TargetView = "Index";
        ViewBag.TargetTitle = "Home Page";
        return PartialView("~/Views/Shared/Redirection.cshtml");
    }

View

You ara redirected to @ViewBag.TargetTitle
<script>
    window.location.href = '@Url.Action(ViewBag.TargetView, ViewBag.TargetCtrl)';
</script>

Now the user will redirect to the Home page and wont see the Home Page as partial view.

1
shdr On

Why not to allow Ajax queries?

add this to your condition:

!filterContext.HttpContext.Request.IsAjaxRequest()