Asp.net MVC Authorize attribute, redirect to custom "no rights" page

mamu picture mamu · Dec 16, 2010 · Viewed 33k times · Source

Asp.net MVC2 does redirect to login page with response 302 when authenticated user has no rights.

I would like to split into two actions

  1. If user is not authenticated then do what it does, redirect to login page.
  2. If user is authenticated but has no required rights then return appropriate http status code and show no rights dude page.

Is there any way to do it? Or am I doing something wrong with authorize and form authentication? Only way I can think of is by writing custom authorize attribute, which I want to avoid.

Answer

hellangle picture hellangle · Dec 16, 2010

You could write custom filter attribute like this:

public class CustomAuthorizeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity == null || !filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" +
                filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
            }

            //Check user right here
            if (userNotRight)
            {
                filterContext.HttpContext.Response.StatusCode = 302;
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }

And use it in controller:

[CustomAuthorize]
public class HomeController : Controller
{

}