Asp.net MVC Authorize attribute, redirect to custom “no rights” page

前端 未结 5 1459
醉梦人生
醉梦人生 2021-01-31 09:08

Asp.net MVC2 does redirect to login page with response 302 when authenticated user has no rights.

I would like to split into two actions

  1. If us
5条回答
  •  执笔经年
    2021-01-31 09:11

    Implement a custom AuthorizeAttribute and add the following override. The basics is to check if user is authenticated but not authorized and then redirect to you own "Access Denied" page. Hope this helps!

    public override void OnAuthorization(AuthorizationContext filterContext) 
    {
        base.OnAuthorization(filterContext);
    
        // Check if user is authenticated and if this action requires authorization
        if (filterContext.HttpContext.User.Identity.IsAuthenticated
            && filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), true)
            || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AuthorizeAttribute), true))
        {
            List attributes = new List(filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true));
            attributes.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true));
    
            // Check all authorzation attributes
            foreach (var attribute in attributes)
            {
                var authAttribute = attribute as AuthorizeAttribute;
                if (authAttribute != null)
                {
                    if (!filterContext.HttpContext.User.IsInRole(authAttribute.Roles))
                    {
                        // User is not authorized so redirect to our access denied error page
                        filterContext.Result = new RedirectToRouteResult(
                            new RouteValueDictionary 
                                {
                                    { "area", "" },
                                    { "controller", "Error" },
                                    { "action", "AccessDenied" }
                                });
                        break;
                    }
                }
            }
        }
    }
    
        

    提交回复
    热议问题