Customizing authorization in ASP.NET MVC

You can build your own authorize attribute like this:

public class ClubAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
  base.OnAuthorization(filterContext);
  if (filterContext.Cancel && filterContext.Result is HttpUnauthorizedResult)
  {
    filterContext.Result = new RedirectToRouteResult(
      new RouteValueDictionary {
      { "clubShortName", filterContext.RouteData.Values[ "clubShortName" ] },
      { "controller", "Account" },
      { "action", "Login" },
      { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
    });
  }
}
}

I used this to redirect to a specific club in a club membership site I am building. You could adapt this to your need. BTW, in my case I do redirect to the login page, but I check to see if the user is authorized and if so, display a message that they don’t have the correct permissions. No doubt you could also add something to ViewData or TempData to display on the page, but I haven’t tried that

EDIT
AuthorizationContext.Cancel doesn’t exist anymore in RC. “filterContext.Result is HttpUnauthorizedResult” seems to be enough : What happened to filterContext.Cancel (ASP.NET MVC)

Leave a Comment