ASP.NET MVC 4自定义授权属性 - 如何将未经授权的用户重定向到错误页面?

23

我正在使用自定义授权属性来根据用户的权限级别授权其访问。如果未经授权的用户(例如,用户尝试删除发票但没有删除访问级别)需要重定向到访问被拒绝页面。

自定义属性正在工作。但在未经授权的用户访问的情况下,浏览器中没有显示任何内容。

控制器代码。

public class InvoiceController : Controller
{
    [AuthorizeUser(AccessLevel = "Create")]
    public ActionResult CreateNewInvoice()
    {
        //...

        return View();
    }

    [AuthorizeUser(AccessLevel = "Delete")]
    public ActionResult DeleteInvoice(...)
    {
        //...

        return View();
    }

    // more codes/ methods etc.
}

自定义属性类代码。

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        if (privilegeLevels.Contains(this.AccessLevel))
        {
            return true;
        }
        else
        {
            return false;
        }            
    }
}

如果您能分享您的经验,我们将不胜感激。

1个回答

71

您需要按照此处指定的方式覆盖HandleUnauthorizedRequest

public class CustomAuthorize: AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if(!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
        else
        {
            filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new{ controller = "Error", action = "AccessDenied" }));
        }
    }
}

注:更新条件语句于2016年1月


2
可能是重复问题。请参考Ben Cull在这里的回答,他解决了这个答案没有涉及到的线程安全问题。 - meataxe
另外,应该这样写: if (false == filterContext.HttpContext.User.Identity.IsAuthenticated) - phandinhlan
如果重定向的目标操作需要参数,你会如何将其传递给函数?例如:AcessDenied(string PermissionNeeded) - phandinhlan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接