【问题标题】:Custom Authorize Attribute additional Param?自定义授权属性附加参数?
【发布时间】:2009-09-20 14:15:41
【问题描述】:

我正在寻找一种方法来自定义我的授权属性,以便我可以使用自己的 MembershipProvider 正确实现它。

例如,我需要拥有 IsInRoles(string role, int perm),换句话说,我希望将其替换为新的 IsinRoles,或者创建另一种方法来存档此结果。

有可能吗?或者我需要写一个不同的授权属性?

非常感谢您的关心...

PS:我正在使用 ASP.net MVC,所以我需要启动并运行 [Authorize] 过滤器。

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    我认为您可以在自定义 AuthorizeAttribute 中添加一个公共属性。

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// Add the allowed roles to this property.
        /// </summary>
        public YourCustomRoles RequiredRole;
    
        public int YourCustomValue;
    
        /// <summary>
        /// Checks to see if the user is authenticated and has the
        /// correct role to access a particular view.
        /// </summary>        
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null) throw new ArgumentNullException("httpContext");
    
            // Make sure the user is authenticated.
            if (httpContext.User.Identity.IsAuthenticated == false) return false;
    
            // Can use your properties if needed and do your checks
            bool authorized = DoSomeCustomChecksHere();
    
            return authorized;
        }
    }
    

    我认为的用法(虽然没有尝试过):

    [CustomAuthorizeAttribute (RequiredRole=MyCustomRole.Role1 | MyCustomRole.Role2, YourCustomValue=1234)]
    

    【讨论】:

    • 它是否可以像控制器之前的 [Authorize.IsInRole("xxx")] 过滤器一样工作?谢谢
    • 谢谢你,只需将它实现到我的新授权类并在控制器过滤器中调用它。 :)
    猜你喜欢
    • 1970-01-01
    • 2011-07-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多