【问题标题】:ASP.NET - Redirect to Error Page if Roles Authorization FailsASP.NET - 如果角色授权失败,则重定向到错误页面
【发布时间】:2011-11-18 20:21:43
【问题描述】:

我正在使用带有表单身份验证的 MVC 3。在我的控制器或方法上,我正在执行以下操作:

[Authorize (Roles = "developer")]

在这种情况下,我想检查用户是否已登录,如果没有,则将其返回到登录页面。但是,如果该用户的“IsInRole”检查返回 false,我希望他们转到显示“未授权”之类的不同视图。

完成这样的事情的最佳方法是什么?我希望避免创建新的 Authorization 属性,因此我不必重构整个应用程序中的每个 Authorize 属性,但如果这是必需的,我会走这条路。

【问题讨论】:

    标签: c# .net asp.net-mvc authentication forms-authentication


    【解决方案1】:

    你可以这样使用它。因为如果你没有权限,它就会出现方法。 不需要授权控制

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                // The user is not authenticated
                base.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "~/Views/Shared/Unauthorized.cshtml",
                };
            }
        }
    

    【讨论】:

      【解决方案2】:

      您也可以使用 401 状态代码的自定义错误页面来执行此操作。

      有关实施细节,请参阅this question

      【讨论】:

        【解决方案3】:

        覆盖HandleUnauthorizedRequest 方法的自定义授权属性可以完成这项工作:

        public class MyAuthorizeAttribute : AuthorizeAttribute
        {
            protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            {
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    // The user is not authenticated
                    base.HandleUnauthorizedRequest(filterContext);
                }
                else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
                {
                    // The user is not in any of the listed roles => 
                    // show the unauthorized view
                    filterContext.Result = new ViewResult
                    {
                        ViewName = "~/Views/Shared/Unauthorized.cshtml"
                    };
                }
                else
                { 
                    base.HandleUnauthorizedRequest(filterContext);
                }
            }
        }
        

        然后:

        [MyAuthorize(Roles = "developer")]
        public ActionResult Develop()
        {
            ...
        }
        

        【讨论】:

        • 你把这个自定义实现放在哪里?
        • @darin-dimitrov 我们应该将自定义实现保存在哪里,是否有约定/建议?
        猜你喜欢
        • 2019-10-01
        • 1970-01-01
        • 2011-07-23
        • 1970-01-01
        • 2010-11-18
        • 2019-06-09
        • 1970-01-01
        • 2014-07-27
        • 2020-12-18
        相关资源
        最近更新 更多