views:

129

answers:

1

I have a scenario that I haven't been able to solve:

I'm toying around with creating my own custom authorization attribute for mvc. The main bit of functionality I would like to add is to have the ability to change where the user gets redirected if they are not in a certain role. I don't mind that the system sends them back to the login page if they're not authenticated, but I would like to choose where to send them if they are authenticated but not allowed to access that action method.

Here's is what I would like to do:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
        public string Action;
        public string Controller;

        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            // if User is authenticated but not in the correct role
            string url = Url.Action(this.Action, this.Controller);                
            httpContext.Response.Redirect(url);
        }
    }

And as an added bonus I would like to have access to ViewContext and TempData before I do the redirect.

Any thoughts on how I could get instantiate a UrlHelper and ViewContext in the attribute?

+4  A: 

You could override the OnAuthorization method:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    if (filterContext == null)
    {
        throw new ArgumentNullException("filterContext");
    }

    // Call the AuthorizeCore which should return true or false
    if (!this.AuthorizeCore(filterContext.HttpContext))
    {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary()
        {
            { "controller", "home" },
            { "action", "about" },
            { "id", "foo" },
        });
    }
}

As far as ViewData and TempData are concerned: filterContext.Controller.ViewData and filterContext.Controller.TempData should work inside the OnAuthorization method. And finally if you wish to use an UrlHelper (in this case there's no need because RedirectToRouteResult is better) you could instantiate it:

var urlHelper = new UrlHelper(filterContext.RequestContext);
Darin Dimitrov
Brilliant, thx. After looking at your response I realized I could have simply asked "How do I go about getting the AuthorizationContext." Once I have that I'm dangerous.
DM
Note: Implementing an OnAuthorization() method is not a trivial exercise. If you choose to override OnAuthorization() instead of AuthorizeCore(), please add code in OnAuthorization() to disable or hook output caching. See http://forums.asp.net/p/1533590/3737756.aspx for more information.
Levi