nacho10f
nacho10f

Reputation: 5876

Help with asp.net mvc authorization

Im using asp.net mvc built in authorize filter. My only problem with it is that I dont want it to redirect my user to a login page when they dont have permission to perform a certain action... It always takes them to the login page even though ther are already logged on (but not with admin role).. I would like to be able to decide where to take them after they tried to perform an action ther arent allowed to..anyone?

Upvotes: 1

Views: 126

Answers (2)

David Glenn
David Glenn

Reputation: 24522

As Levi said you need to create your own custom AttributeFilter by overriding AthorizeAttribute. Something like

public class CustomAuthorizeAttribute : AuthorizeAttribute {

  public string Url { get; set; }

  public override void OnAuthorization(AuthorizationContext filterContext) {
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { //or custom authorization logic
      filterContext.HttpContext.Response.Redirect(Url);
    }
    base.OnAuthorization(filterContext);
  }

 }


[CustomAuthorizeAttribute(Url="/Admin/AccessDenied")]
public ActionResult Admin() {
  return View();
}

Taken from this similar question

Upvotes: 0

Levi
Levi

Reputation: 32818

Subclass AuthorizeAttribute and override the HandleAuthorizationFailed() method. The default logic of this method is that it sets the context's result to an HttpUnauthorizedResult, but you could do anything you want from this method. Then attribute the target method with this new attribute.

Upvotes: 2

Related Questions