Exemplo n.º 1
0
        /// <summary>Called when a process requests authorization.</summary>
        /// <param name="filterContext">The filter context, which encapsulates information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute" />.</param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="filterContext" /> parameter is null.</exception>
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
            {
                throw new InvalidOperationException("AuthorizeAttribute_CannotUseWithinChildActionCache");
            }
            bool flag = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);

            if (flag)
            {
                return;
            }
            if (this.AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
                cache.SetProxyMaxAge(new TimeSpan(0L));
                cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
                return;
            }
            this.HandleUnauthorizedRequest(filterContext);
        }
Exemplo n.º 2
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            //排除验证的Action
            if (this.ForNotAuthorityUrl != null)
            {
                string excludeAction     = filterContext.RequestContext.RouteData.GetRequiredString("action").ToUpper();
                string excludeController = filterContext.RequestContext.RouteData.GetRequiredString("controller").ToUpper();
                string currentUrl        = "{0}/{1}".With(excludeController, excludeAction);
                if (this.ForNotAuthorityUrl.Any(z => z.ToUpper().Equals(currentUrl)))
                {
                    return;//此Action不需要特殊验证,返回。
                }
            }

            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }



            if (AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                var returnUrl = "{0}/WX/WeixinOAuth/MpCallback?callbackUrl={1}"
                                .With(SiteConfig.DomainName, SiteConfig.DomainName + filterContext.HttpContext.Request.Url.PathAndQuery.ToString().UrlEncode());
                var getCodeUrl = OAuthApi.GetAuthorizeUrl(SiteConfig.AppId, returnUrl, "Azure", OAuthScope.snsapi_userinfo);
                filterContext.Result = new RedirectResult(getCodeUrl);
            }
        }
Exemplo n.º 3
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            bool inherit = true;

            if (!filterContext.IsChildAction &&
                !filterContext.ActionDescriptor.IsDefined(typeof(HtmlAllowedAttribute), inherit) &&
                !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(HtmlAllowedAttribute), true))
            {
                if (this.AuthorizeInternal(filterContext.HttpContext))
                {
                    HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
                    cache.SetProxyMaxAge(new TimeSpan(0L));
                    cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
                }
                else
                {
                    this.HandleNonHttpsRequest(filterContext);
                }
            }
        }
        public virtual void OnAuthentication(AuthenticationContext filterContext)
        {
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

            if (skipAuthorization)
            {
                return;
            }

            IUser user;
            var   principal = filterContext.Principal;

            if (principal == null || principal.Identity == null || !principal.Identity.IsAuthenticated || !TryGetUser(principal, out user))
            {
                HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                OnAuthenticated(filterContext, user);
            }

            if (filterContext.Result != null)
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
        }
Exemplo n.º 5
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (AuthorizeCore(filterContext.HttpContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                    {
                        controller = "Account",
                        action     = "Unauthorised"
                    })
                        );
                }
                else
                {
                    base.HandleUnauthorizedRequest(filterContext);
                }
            }
        }
Exemplo n.º 6
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                var urlHelper = new UrlHelper(filterContext.RequestContext);

                filterContext.Result = new RedirectResult(urlHelper.Action(MVC.Accounts.LogIn(filterContext.HttpContext.Request.Url.PathAndQuery)));
                return;
            }

            if (!AuthorizeCore(filterContext.HttpContext))
            {
                var urlHelper = new UrlHelper(filterContext.RequestContext);

                filterContext.Result = new RedirectResult(urlHelper.Action(MVC.Accounts.Unauthorized(filterContext.HttpContext.Request.Url.PathAndQuery)));
                return;
            }

            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            cache.SetProxyMaxAge(new TimeSpan(0));
            cache.AddValidationCallback(CacheValidateHandler, null);
        }
Exemplo n.º 7
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cachePolicy =
                    filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null);
            }

            /// This code added to support custom Unauthorized pages.
            else if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (NotifyUrl != null)
                {
                    filterContext.Result = new RedirectResult(NotifyUrl);
                }
                else
                {
                    // Redirect to Login page.
                    HandleUnauthorizedRequest(filterContext);
                }
            }
            /// End of additional code
            else
            {
                // Redirect to Login page.
                HandleUnauthorizedRequest(filterContext);
            }
        }
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                if (IsLogined(filterContext.HttpContext))
                {
                }
                else
                {
                    var callbackUrl = Senparc.Weixin.HttpUtility.UrlUtility.GenerateOAuthCallbackUrl(filterContext.HttpContext, _oauthCallbackUrl);
                    var state       = string.Format("{0}|{1}", "FromSenparc", DateTime.Now.Ticks);
                    var url         = OAuthApi.GetAuthorizeUrl(_appId, callbackUrl, state, _oauthScope);
                    filterContext.Result = new RedirectResult(url);
                }
            }
        }
Exemplo n.º 9
0
        private void SetCachePolicy(AuthorizationContext context)
        {
            HttpCachePolicyBase policy = context.HttpContext.Response.Cache;

            policy.SetProxyMaxAge(new TimeSpan(0));
            policy.AddValidationCallback(CacheValidateHandler, null);
        }
Exemplo n.º 10
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                // auth failed, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
Exemplo n.º 11
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
            {
                // If a child action cache block is active, we need to fail immediately, even if authorization
                // would have succeeded. The reason is that there's no way to hook a callback to rerun
                // authorization before the fragment is served from the cache, so we can't guarantee that this
                // filter will be re-run on subsequent requests.
                throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
Exemplo n.º 12
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
            {
                //throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);
            }

            bool skipAuthorization = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), inherit: true).Any() ||
                                     filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), inherit: true).Any();

            if (skipAuthorization)
            {
                return;
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                HandleUnauthorizedRequest(filterContext);
            }
            base.OnAuthorization(filterContext);
        }
Exemplo n.º 13
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            //if (AuthorizeCore(filterContext.HttpContext))
            if (SecurityHelper.CustomAuthorizeCore(filterContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else// if (!filterContext.Controller.ControllerContext.IsChildAction)
            {
                HandleUnauthorizedRequest(filterContext);
            }
            //else
            //{
            //    filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
            //}
        }
Exemplo n.º 14
0
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (AuthorizeCore(filterContext.HttpContext))
        {
            // ** IMPORTANT **
            // Since we're performing authorization at the action level, the authorization code runs
            // after the output caching module. In the worst case this could allow an authorized user
            // to cause the page to be cached, then an unauthorized user would later be served the
            // cached page. We work around this by telling proxies not to cache the sensitive page,
            // then we hook our custom authorization code into the caching mechanism so that we have
            // the final say on whether a page should be served from the cache.

            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
            cachePolicy.SetProxyMaxAge(new TimeSpan(0));
            cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);

            if (!_hasPermission)
            {
                filterContext.Result = new RedirectResult("/YourHasNoPermissionUrl")
            }
        }
        else
        {
            filterContext.Result = new RedirectResult("/YourUnauthorizedUrl")
        }
    }
        /// <summary>
        /// This method accepts just one parameter as AuthorizationContext which is derived from ControllerContext
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("Context");
            }

            // This part of code is from microsoft
            bool isAuthorizationDisable = filterContext.ActionDescriptor.IsDefined
                                              (typeof(AllowAnonymousAttribute), inherit: true) ||
                                          filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(
                typeof(AllowAnonymousAttribute), inherit: true);

            if (isAuthorizationDisable)
            {
                return;
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null);
            }
            else
            {
                filterContext.Result = new HttpUnauthorizedResult("Not authorized");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 在需要授权时调用。
        /// </summary>
        /// <param name="filterContext">筛选器上下文。</param>
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
            {
                throw new InvalidOperationException("AuthorizeAttribute_CannotUseWithinChildActionCache");
            }
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }
            IFunction           function = filterContext.GetExecuteFunction(ServiceProvider);
            AuthorizationResult result   = AuthorizeCore(filterContext.HttpContext, function);

            if (result.ResultType != AuthorizationResultType.Allowed)
            {
                HandleUnauthorizedRequest(filterContext, result);
            }
            else
            {
                HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
                cache.SetProxyMaxAge(new TimeSpan(0L));
                cache.AddValidationCallback(CacheValidateHandler, function);
            }
        }
Exemplo n.º 17
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!Authenticate(filterContext.HttpContext))
            {
                // HttpCustomBasicUnauthorizedResult inherits from HttpUnauthorizedResult and does the
                // work of displaying the basic authentication prompt to the client
                filterContext.Result = new HttpCustomBasicUnauthorizedResult();
            }
            else
            {
                // AuthorizeCore is in the base class and does the work of checking if we have
                // specified users or roles when we use our attribute
                if (AuthorizeCore(filterContext.HttpContext))
                {
                    HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                    cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                    cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
                }
                else
                {
                    // auth failed, display login

                    // HttpCustomBasicUnauthorizedResult inherits from HttpUnauthorizedResult and does the
                    // work of displaying the basic authentication prompt to the client
                    filterContext.Result = new HttpCustomBasicUnauthorizedResult();
                }
            }
        }
Exemplo n.º 18
0
        protected virtual void HandleAuthorizedRequest(AuthorizationContext filterContext)
        {
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;

            cachePolicy.SetProxyMaxAge(new TimeSpan(0));
            cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
        }
Exemplo n.º 19
0
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) ||
                                     filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

            if (skipAuthorization)
            {
                return;
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null);
            }
            else
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
Exemplo n.º 20
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                // auth failed, redirect to login page
                if (filterContext.HttpContext.User.Identity.IsAuthenticated &&
                    _rolesSplit.Length > 0)
                {
                    PermissaoValidar validar = new PermissaoValidar();
                    validar.Verificar(_rolesSplit.Select(x => (ePermissao)Enum.Parse(typeof(ePermissao), x)).ToArray());
                }

                if (filterContext.HttpContext.User.Identity.IsAuthenticated && filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult
                    {
                        Data = new
                        {
                            MsgPermissoes = Validacao.Erros
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };

                    filterContext.HttpContext.Response.StatusCode = 500;
                    //filterContext.HttpContext.Response.SubStatusCode = 1;
                    filterContext.HttpContext.Response.StatusDescription      = Mensagem.Concatenar(Validacao.Erros.Select(x => x.Texto).ToList());
                    filterContext.HttpContext.Response.SuppressContent        = false;
                    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                }
                else
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                    //string url = Validacao.QueryParamSerializer(FormsAuthentication.LoginUrl);
                    //filterContext.Result = new RedirectResult(url);
                }
            }
        }
        public virtual void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName     = filterContext.ActionDescriptor.ActionName;

            List <string> UserPermissions = GetCurrentPermissions();

            if (UserPermissions != null && UserPermissions.Count() > 0)
            {
                _userPermissionsSplit = UserPermissions.Union(_userPermissionsSplit).ToArray();
                //if (!string.IsNullOrWhiteSpace(this.Permissions))
                //{
                //    List<string> users = this.Permissions.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                //    this.Permissions = string.Join(",", Permissions.Union(users).ToArray());
                //}
                //else
                //{
                //    this.Permissions = string.Join(",", Permissions.ToArray());
                //}
            }

            List <string> Permissions = GetPermissions(actionName, controllerName);

            if (Permissions != null && Permissions.Count() > 0)
            {
                _permissionsSplit = Permissions.Union(_permissionsSplit).ToArray();
                //if (!string.IsNullOrWhiteSpace(this.Permissions))
                //{
                //    List<string> users = this.Permissions.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                //    this.Permissions = string.Join(",", Permissions.Union(users).ToArray());
                //}
                //else
                //{
                //    this.Permissions = string.Join(",", Permissions.ToArray());
                //}
            }

            if (AuthorizeCore(filterContext.HttpContext))//根据验证判断进行处理
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                HandleNopermissionsResult(filterContext);
            }
        }
Exemplo n.º 22
0
        protected void SetCachePolicy(AuthorizationContext filterContext)
        {
            // ** IMPORTANT ** Since we're performing authorization at the action level, the
            // authorization code runs after the output caching module. In the worst case this could
            // allow an authorized user to cause the page to be cached, then an unauthorized user
            // would later be served the cached page. We work around this by telling proxies not to
            // cache the sensitive page, then we hook our custom authorization code into the caching
            // mechanism so that we have the final say on whether a page should be served from the cache.
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;

            cachePolicy.SetProxyMaxAge(new TimeSpan(0));
            cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Indica como será a política de cache para o contexto em questão.
        /// </summary>
        /// <param name="filterContext">Contexto do atributo.</param>
        protected void SetCachePolicy(AuthorizationContext filterContext)
        {
            // ** IMPORTANTE **
            // Quando estamos realizando uma autorização à nivel de action, o codigo de autorização
            // roda após o modulo de caching de saída (output caching module). No pior caso, isso
            // pode permitir que um usuário autorizado deixe em cache uma página, deste modo um
            // usuário não autorizado poderá depois acessar a página em cache. Para poder evitar isso
            // nós informamos aos proxies para não deixar em cache a página.
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;

            cachePolicy.SetProxyMaxAge(TimeSpan.Zero);
            cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var granted = AuthorizeCore(filterContext.HttpContext);

            if (granted)
            {
                HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
                cache.SetProxyMaxAge(new TimeSpan(0L));
                cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), (object)null);
            }
            else
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            ////需要特殊验证的Action
            //if (this.ForAuthorityActionsPrefix != null)
            //{
            //    string actionName = filterContext.RequestContext.RouteData.GetRequiredString("action").ToUpper();
            //    if (this.ForAuthorityActionsPrefix.FirstOrDefault(p => actionName.StartsWith(p.ToUpper())) == null)
            //    {
            //        return;//此Action不需要特殊验证,返回。
            //    }
            //}

            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            //判断不能用IP直接登录
            var url = filterContext.HttpContext.Request.Url.Host;

            if (AuthorizeCore(filterContext.HttpContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                // auth failed, redirect to login page

                //if (filterContext.RouteData.DataTokens["area"] != null
                //    && filterContext.RouteData.DataTokens["area"].ToString().ToUpper() == "ADMIN")
                //{
                //    filterContext.Controller.TempData["AdminLogin"] = true;
                //}

                //todo: to a special page
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            string auth = filterContext.HttpContext.Request.Headers["Authorization"];

            if (!String.IsNullOrEmpty(auth))
            {
                byte[] encodedDataAsBytes = Convert.FromBase64String(auth.Replace("Basic ", ""));
                string value    = Encoding.ASCII.GetString(encodedDataAsBytes);
                string username = value.Substring(0, value.IndexOf(':'));
                string token    = value.Substring(value.IndexOf(':') + 1);

                if (Repository.ErpUserRepo.IsValidToken(new Model.ErpUser()
                {
                    Username = username, Token = Guid.Parse(token)
                }))
                {
                    filterContext.HttpContext.User = new GenericPrincipal(new GenericIdentity(username), null);
                }
                else
                {
                    filterContext.Result = new HttpStatusCodeResult(401);
                }
            }
            else
            {
                if (AuthorizeCore(filterContext.HttpContext))
                {
                    HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                    cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                    cachePolicy.AddValidationCallback(CacheValidateHandler, null);
                }
                else
                {
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusDescription = "Unauthorized";
                    filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"");
                    filterContext.HttpContext.Response.Write("401, please authenticate");
                    filterContext.HttpContext.Response.StatusCode = 401;
                    filterContext.Result = new EmptyResult();
                    filterContext.HttpContext.Response.End();
                }
            }
        }
Exemplo n.º 27
0
 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     if (filterContext == null)
     {
         throw new ArgumentNullException("filterContext");
     }
     if (this.AuthorizeCore(filterContext.HttpContext))
     {
         HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
         cache.SetProxyMaxAge(new TimeSpan(0L));
         cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
     }
     else
     {
         this.HandleUnauthorizedRequest(filterContext);
     }
 }
Exemplo n.º 28
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null);
            }
            else
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
        /*protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
         * {
         *  OnAuthorizationx(filterContext);
         * }
         *
         * protected override bool AuthorizeCore(HttpContextBase httpContext)
         * {
         *  return false;
         * }*/

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            string auth = filterContext.HttpContext.Request.Headers["Authorization"];

            if (!String.IsNullOrEmpty(auth))
            {
                var userData = new UserData();
                var authType = auth.ToLowerInvariant();
                if (authType.StartsWith("basic "))
                {
                    AuthWithBasic(auth, userData);
                }

                if (ValidateUser(userData.UserName, userData.Password))
                {
                    filterContext.HttpContext.User = new GenericPrincipal(new GenericIdentity(userData.UserName), null);
                }
                else
                {
                    if (!IsEventual)
                    {
                        filterContext.Result = new HttpStatusCodeResult(401);
                    }
                }
            }
            else
            {
                if (AuthorizeCore(filterContext.HttpContext))
                {
                    HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                    cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                    cachePolicy.AddValidationCallback(CacheValidateHandler, null);
                }
                else
                {
                    //Basic auth is standard
                    ResponseUnauthorized(filterContext, "Basic realm=\"Secure Area\"");
                }
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public virtual void OnAuthorization([NotNull] AuthorizationContext filterContext)
        {
            Invariant.IsNotNull(filterContext, "filterContext");

            if (filterContext.IsChildAction)
            {
                return;
            }

            if (IsAuthorized(filterContext))
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;

                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, filterContext);
            }
            else
            {
                HandleUnauthorized(filterContext);
            }
        }