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?
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With