【问题标题】:Authorize attribute created controller for non-authorized users为非授权用户授权属性创建控制器
【发布时间】:2014-10-21 06:39:34
【问题描述】:

我有一个带有 Authorize 属性的控制器。如果用户未经授权,我预计不会创建控制器。但似乎确实如此。有什么方法可以改变这种行为并在不创建控件本身的情况下使 Authorize 生成 401 响应?

我为什么需要这个?我有一些面向管理员的控制器,它们仅针对经过身份验证的用户。它在基本控制器的构造函数中有一些逻辑。目前我必须检查用户是否为空,这似乎是一种浪费。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    您可以从AuthorizeAttribute 派生并以您想要的方式处理它。该请求将首先访问这个被覆盖的方法,让您有机会决定是允许进一步处理请求还是拒绝它。您还可以通过添加 AllowAnonymous 属性来选择忽略特定方法(例如 Login),或者通过从 Attribute 类派生来定义您自己的属性。

    一个工作示例如下:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class RdbiAuthorizationAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// Verifies that the logged in user is a valid organization user.
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            Guard.ArgumentNotNull(filterContext, "filterContext");
            Guard.ArgumentNotNull(filterContext.Controller, "filterContext.Controller");
    
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(
                typeof(AllowAnonymousAttribute), inherit: true)
                                     || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(
                                         typeof(AllowAnonymousAttribute), inherit: true);
    
            if (skipAuthorization)
            {
                return;
            }
    
            if (string.IsNullOrEmpty(filterContext.HttpContext.User.Identity.Name))
                throw new AuthenticationException("User must be logged in to access this page.");
    
            var controller = filterContext.Controller as BaseController;
            if (controller != null)
            {
                var user = controller.GetUser();
    
                if (user == null)
                {
                    throw new InvalidOperationException(string.Format("Logged in user {0} is not a valid user", filterContext.HttpContext.User.Identity.Name));
                }
            }
    
            base.OnAuthorization(filterContext);
        }
    }
    

    【讨论】:

    • 如果你提供的代码是正确的,filterContext.Controller 已经包含了一个控制器的实例。所以无论我在 OnAuthorization 中写什么,它都不会改变 Controller 已经实例化的事实。
    • 我不明白你为什么关心控制器是否实例化。如果您处理该请求,您可以向用户返回适当的响应 (401),并且他将无法访问他无权访问的任何资源。我错过了你的要求吗?
    猜你喜欢
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多