Exemplo n.º 1
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var httpContext = filterContext.HttpContext;

            httpContext.Items["MVCLearn_IsAuthorized"]   = false;
            httpContext.Items["MVCLearn_AuthorizeState"] = AuthorizeState.没有登录;

            var area       = filterContext.RouteData.DataTokens["area"]?.ToString().ToLower();
            var controller = filterContext.RouteData.Values["controller"]?.ToString().ToLower();
            var action     = filterContext.RouteData.Values["action"]?.ToString().ToLower();
            var url        = "/" + area + "/" + controller + "/" + action;

            if ("/admin/account/login" == url)
            {
                httpContext.Items["MVCLearn_IsAuthorized"] = true;
            }
            else
            {
                var authorizeId = httpContext.Request.Cookies["MVCLearn_AuthorizeId"];
                if (authorizeId != null)
                {
                    IPrivilegeService service = new PrivilegeService(httpContext);// todo:全局filter依赖注入
                    var authorize             = service.GetAuthorize(authorizeId.Value);
                    if (authorize != null)
                    {
                        var privilege    = service.GetPrivilege(authorize.User.UserID);
                        var isAuthorized = privilege.Accesses.Any(e => e.Url == url);
                        if (isAuthorized)
                        {
                            httpContext.Items["MVCLearn_IsAuthorized"] = true;
                            httpContext.Items["MVCLearn_Authorize"]    = authorize;
                            httpContext.Items["MVCLearn_Privilege"]    = privilege; // 缓存当前用户权限

                            /*
                             * GenericIdentity identity = new GenericIdentity(authorizeId.Value);
                             * IPrincipal principal = new GenericPrincipal(identity, new[] { "" });
                             * httpContext.User = principal;
                             */
                        }
                        else // 没有权限
                        {
                            httpContext.Items["MVCLearn_AuthorizeState"] = AuthorizeState.没有权限;
                        }
                    }
                    else // 传来了认证,但是服务器没通过
                    {
                        // httpContext.Items["MVCLearn_AuthorizeType"] = AuthorizeState.认证失败;
                    }
                }
            }
            base.OnAuthorization(filterContext);
        }