Ejemplo n.º 1
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            // 在關閉瀏覽器或者切換使用者時,刪除快取資料 (http://blog.toright.com/posts/3414/初探-http-1-1-cache-機制.html)
            cache.SetCacheability(HttpCacheability.Public);

            // 在 http response header 裡設 expire time 減少 client 送出 http request (http://fcamel-life.blogspot.tw/2010/06/http-response-header-expire-request.html)
            cache.SetExpires(DateTime.Now.AddDays(365)); // HTTP/1.0
            // filterContext.HttpContext.Response.Cache.SetValidUntilExpires(true);

            cache.SetMaxAge(TimeSpan.FromDays(365));      // HTTP/1.1, Cache-Control: max-age
            cache.SetProxyMaxAge(TimeSpan.FromDays(365)); // HTTP/1.1, Cache-Control: s-maxage

            cache.SetETagFromFileDependencies();
            cache.SetLastModifiedFromFileDependencies();
            cache.SetAllowResponseInBrowserHistory(true);

            // http://stackoverflow.com/questions/6151292/httpcontext-current-response-cache-setcacheabilityhttpcacheability-nocache-not
            // 按下登出按鈕所需要的快取設定
            //cache.SetCacheability(HttpCacheability.NoCache);
            //cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            //cache.SetNoStore();

            // http://stackoverflow.com/questions/4078011/how-to-switch-off-caching-for-mvc-requests-but-not-for-static-files-in-iis7
            // 關閉 Cache 功能
            //cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            //cache.SetValidUntilExpires(false);
            //cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            //cache.SetCacheability(HttpCacheability.NoCache);
            //cache.SetNoStore();
        }
Ejemplo n.º 2
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);
        }
Ejemplo 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 */);
            }
        }
Ejemplo 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);
                }
            }
        }
Ejemplo n.º 6
0
        public void Apply(HttpCachePolicyBase policy)
        {
            policy.ThrowIfNull("policy");

            if (!_hasPolicy)
            {
                return;
            }

            switch (_cacheability)
            {
            case HttpCacheability.NoCache:
                policy.SetCacheability(_allowsServerCaching == true ? HttpCacheability.ServerAndNoCache : HttpCacheability.NoCache);
                break;

            case HttpCacheability.Private:
                policy.SetCacheability(_allowsServerCaching == true ? HttpCacheability.ServerAndPrivate : HttpCacheability.Private);
                break;

            case HttpCacheability.Public:
                policy.SetCacheability(HttpCacheability.Public);
                break;
            }
            if (_noStore == true)
            {
                policy.SetNoStore();
            }
            if (_noTransforms == true)
            {
                policy.SetNoTransforms();
            }
            if (_clientCacheExpirationUtcTimestamp != null)
            {
                policy.SetExpires(_clientCacheExpirationUtcTimestamp.Value);
            }
            if (_clientCacheMaxAge != null)
            {
                policy.SetMaxAge(_clientCacheMaxAge.Value);
            }
            if (_allowResponseInBrowserHistory != null)
            {
                policy.SetAllowResponseInBrowserHistory(_allowResponseInBrowserHistory.Value);
            }
            if (_eTag != null)
            {
                policy.SetETag(_eTag);
            }
            if (_omitVaryStar != null)
            {
                policy.SetOmitVaryStar(_omitVaryStar.Value);
            }
            if (_proxyMaxAge != null)
            {
                policy.SetProxyMaxAge(_proxyMaxAge.Value);
            }
            if (_revalidation != null)
            {
                policy.SetRevalidation(_revalidation.Value);
            }
        }
Ejemplo n.º 7
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
            string actionName     = filterContext.ActionDescriptor.ActionName.ToLower();


            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (AuthorizeCore(filterContext.HttpContext))
            {
                //if (a.Check(filterContext.HttpContext.User.Identity.GetUserId(), controllerName, actionName))
                if (UserRepository.CheckAdminRole(filterContext.HttpContext.User.Identity.Name))
                {
                    HttpCachePolicyBase cachePolicy =
                        filterContext.HttpContext.Response.Cache;
                    cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                }
                else
                {
                    filterContext.Result = new RedirectResult(NotifyUrl);
                }
            }
            else
            {
                filterContext.Result = new RedirectResult(NotifyUrl);
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 ///     Wird aufgerufen, wenn eine Autorisierung erforderlich ist.
 /// </summary>
 /// <param name="filterContext">Der Filterkontext.</param>
 public virtual void OnAuthorization(AuthorizationContext filterContext)
 {
     if (filterContext == null)
     {
         throw new ArgumentNullException("filterContext");
     }
     if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
     {
         throw new InvalidOperationException("Can't use this attribute with ChildActionCache.");
     }
     if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
         filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
     {
         return;
     }
     if (AuthorizeCore(filterContext.HttpContext))
     {
         HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
         cache.SetProxyMaxAge(new TimeSpan(0L));
         cache.AddValidationCallback(CacheValidateHandler, null);
     }
     else
     {
         HandleUnauthorizedRequest(filterContext);
     }
 }
Ejemplo n.º 9
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();
                }
            }
        }
Ejemplo n.º 10
0
        protected virtual void HandleAuthorizedRequest(AuthorizationContext filterContext)
        {
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;

            cachePolicy.SetProxyMaxAge(new TimeSpan(0));
            cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
        }
Ejemplo n.º 11
0
        private void SetCachePolicy(AuthorizationContext context)
        {
            HttpCachePolicyBase policy = context.HttpContext.Response.Cache;

            policy.SetProxyMaxAge(new TimeSpan(0));
            policy.AddValidationCallback(CacheValidateHandler, null);
        }
        /// <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");
            }
        }
Ejemplo n.º 13
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);
            }
        }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
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);
            //}
        }
Ejemplo n.º 16
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

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

            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 /* data */);
            }
            else
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
Ejemplo n.º 17
0
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        _filterContext = filterContext;

        if (!Authenticate(filterContext.HttpContext))
        {
            filterContext.Result = new HttpBasicUnauthorizedResult();
        }
        else
        {
            if (AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null);
            }
            else
            {
                filterContext.Result = new HttpBasicUnauthorizedResult();
            }
        }
    }
Ejemplo n.º 18
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);
            }
        }
Ejemplo n.º 19
0
 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     Guard.ArgumentNotNull(filterContext, nameof(filterContext));
     if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
     {
         throw new InvalidOperationException("AuthorizeAttribute can not use within Child action cache");
     }
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
     {
         HandleUnauthorizedRequest(filterContext);
         return;
     }
     if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
     {
         if (this.AuthorizeCore(filterContext.HttpContext))
         {
             HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
             cache.SetProxyMaxAge(new TimeSpan(0L));
             cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
         }
         else
         {
             throw new AuthorizationException();
         }
     }
     if (!_freeBirdAuthorize.IsAuthorized(filterContext, Name))
     {
         throw new AuthorizationException();
     }
 }
Ejemplo n.º 20
0
        public 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
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
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")
        }
    }
        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);
                }
            }
        }
Ejemplo n.º 24
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);
            }
        }
Ejemplo n.º 25
0
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (Authorize(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();
            }
        }
Ejemplo n.º 26
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);
                }
            }
        }
Ejemplo n.º 27
0
 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     if (IsAuthorize(filterContext.HttpContext))
     {
         HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
         cachePolicy.SetProxyMaxAge(new TimeSpan(0));
     }
     else
     {
         base.HandleUnauthorizedRequest(filterContext);
     }
 }
        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);
            }
        }
Ejemplo n.º 29
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 */);
        }
Ejemplo n.º 30
0
        public new void OnResultExecuted(ResultExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetValidUntilExpires(false);
            cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            cache.SetNoStore();
            cache.AppendCacheExtension("private");
            cache.AppendCacheExtension("no-cache=Set-Cookie");
            cache.SetProxyMaxAge(TimeSpan.Zero);
        }