4

好的跟进这个线程,这就是我想出的......

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 工作流程如下:

  1. 首先,AuthorizeCore 被触发。如果返回 true,则用户已获得授权。如果返回 false,则触发 HandleUnauthorizedRequest。那正确吗?
  2. 我在某处读到需要使用new关键字来覆盖属性。因此,这就是我覆盖 Roles 属性的方式。但是,如果覆盖属性是初始属性的不同类型(基类中的那个),那会隐藏它还是创建一个完全不同的属性呢?

所以你怎么看?这真的应该工作吗?我现在无法测试它,因为我还没有设置UI(等待设计师完成设计)......事实上,这是我第一次体会到TDD的好处,我曾经认为它完全愚蠢而无用,但我错了:)

PS:在这个线程上,@tvanfosson 正在设置上下文的 CachePolicy(我认为),有人可以解释一下为什么我可能需要这样做吗?

提前致谢。

4

1 回答 1

2
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;
    }
}

在控制器中

[CustomAuthorize("Administrator,Company,OtherRole")]
public ActionResult Test(){
    return View();
}
于 2012-11-16T15:17:18.220 回答