Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect a user to a specific view when authorization fails?

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?

like image 870
mattruma Avatar asked Nov 08 '09 23:11

mattruma


1 Answers

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)]
like image 140
LukLed Avatar answered Nov 15 '22 19:11

LukLed