views:

37

answers:

1

I have the following code:

    [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = RoleKeys.Administrators)]
    public ActionResult Edit(int id, FormCollection collection)
    {
        User user = userRepository.GetUser(id);

        try
        {
            this.UpdateModel(user);

            userRepository.Save();

            return this.RedirectToAction("Details", new { id = user.UserId });
        }
        catch
        {
            this.ModelState.AddModelErrors(user.GetRuleViolations());

            return View(new UserFormViewModel(user));
        }
    }

If the currently logged in user is not in the Administrators role, it kicks them back to the login screen. The user is already logged in, they are just not authorize to perform the requested action.

Is there any way to have them redirected to a specific view, for example, AccessDenied?

+3  A: 

You can define your own attribute:

public class MyAuthorizeAttribute: AuthorizeAttribute
{
    public override void OnAuthorization( AuthorizationContext filterContext )
    {
         base.OnAuthorization(filterContext);
         if (filterContext.Result is HttpUnauthorizedResult)
         {
             filterContext.Result = new RedirectToRouteResult(
             new RouteValueDictionary
             {
                 { "controller", "Login" },
                 { "action", "AccessDenied" }
             });
         }
    }
}

and use

[AcceptVerbs(HttpVerbs.Post), MyAuthorize(Roles = RoleKeys.Administrators)]
LukLed
There doesn't seem to be a filterContext.Cancel property?
mattruma
I just removed the filterContext.Cancel and it all seems to work!
mattruma
Sorry, used some old code, there is no Cancel anymore.
LukLed