asp.net-mvc - 自定义授权属性(后续)

标签 asp.net-mvc asp.net-mvc-3 asp.net-roles asp.net-authorization

好的跟进 this thread ,这就是我想出的……

public class SharweAuthorizeAttribute : AuthorizeAttribute
{
    private bool isAuthenticated = false;
    private bool isAuthorized = false;
    public new string[] Roles { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (SessionManager.CheckSession(SessionKeys.User) == true)
        {
            isAuthenticated = true;
            foreach (string role in Roles)
            {
                if (RolesService.HasRole((string)role))
                    isAuthorized = true;
            }
        }
        return (isAuthenticated && isAuthorized);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!isAuthenticated)
        {
            filterContext.Result = new RedirectToRouteResult(
                            new RouteValueDictionary 
                            {
                                { "action", "User" },
                                { "controller", "Login" }
                            });
        } else if(!isAuthorized) {
            filterContext.Result = new RedirectToRouteResult(
                            new RouteValueDictionary 
                            {
                                { "action", "Home" },
                                { "controller", "Error" }
                            });
        }
    }
}

我是如何/为什么想出这个的?因为我相信 AuthorizeAttribute 工作流程如下:
  • 首先,AuthorizeCore 被触发。如果返回 true,则用户已获得授权。如果返回 false,则触发 HandleUnauthorizedRequest。那正确吗?
  • 我在某处读到我需要使用 new关键字来覆盖属性。因此,这就是我覆盖 Roles 属性的方式。但是,如果覆盖属性与初始属性(基类中的那个)属于不同类型,那是否也会隐藏它或创建一个完全不同的属性呢?

  • 所以你怎么看?这真的应该奏效吗?我现在无法测试,因为我还没有设置UI(等待设计师完成设计)...... 其实这是我第一次体会到TDD的好处,我以前认为它是彻头彻尾的愚蠢而无用,但我错了:)

    P.S:在 this thread ,@tvanfosson 正在设置上下文的 CachePolicy(我认为),有人可以解释一下,为什么我可能需要这样做吗?

    提前致谢。

    最佳答案

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private readonly bool _authorize;
        private readonly string[] _roles;
    
        public CustomAuthorizeAttribute(string roles)
        {
            _authorize = true;
            _roles = roles.Split(',');
        }
    
        public CustomAuthorizeAttribute(string roles, bool isAdminPath)
        {
            _authorize = true;
            _roles = roles.Split(',');
        }
    
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //if controller have role auth and user is not loged
            if(_authorize && !httpContext.User.Identity.IsAuthenticated)
                return false;
    
            // if controller have role auth and user is loged
            if(_roles != null)
            {
                //grab user roles from DB
                var UserRole = RoleRepository.GetUserRole(new Guid(httpContext.User.Identity.Name));
                if (_roles.Contains(UserRole))
                   return true;
            }
            return false;
        }
    }
    

    在 Controller 中
    [CustomAuthorize("Administrator,Company,OtherRole")]
    public ActionResult Test(){
        return View();
    }
    

    关于asp.net-mvc - 自定义授权属性(后续),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5082951/

    相关文章:

    c# - 使用 ASP.net Identity 和 Web API 获取用户角色

    asp.net-mvc - Azure Web 角色中 MVC javascript 包的 gzip 压缩

    c# - 单元测试 Mvc.Compare 属性错误地返回模型 isValid = true

    javascript - 自动完成显示 [object object] 列表项而不是值

    c# - 替换为 .Replace/.Regex

    asp.net - 在 mvc3 中的 Get Call 上将数据从 View 传递到 Controller

    jquery - 在 MVC3、Razor 中使用数据注释时,使用 [Compare ("",..)] 比较新密码并确认新密码不起作用

    c# - Entity Framework : Check all relationships of an entity for foreign key use

    ASP.NET 成员资格/角色 - 如何将用户链接到多个应用程序/角色?

    asp.net - 在新的 VS 2013 Identity UserManager 中动态添加角色