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();
            }
        }
    }
Example #2
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);
            }
        }
        public override void OnActionExecuted(
            ActionExecutedContext filterContext)
        {
            if (Duration < 0)
            {
                return;
            }

            HttpCachePolicyBase cache = filterContext.HttpContext
                                        .Response.Cache;

            if (PreventBrowserCaching)
            {
                cache.SetCacheability(HttpCacheability.NoCache);
                Duration = 0;
            }
            else
            {
                cache.SetCacheability(HttpCacheability.Public);
            }

            TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration);

            cache.SetExpires(DateTime.Now.Add(cacheDuration));
            cache.SetMaxAge(cacheDuration);
            cache.AppendCacheExtension("must-revalidate,"
                                       + "proxy-revalidate");
        }
Example #4
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();
     }
 }
Example #5
0
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            cache.SetCacheability(HttpCacheability.NoCache);
            base.OnResultExecuted(filterContext);
        }
Example #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);
        }
Example #7
0
        private static void SetHeaders(BundleResponse response, BundleContext context, bool noCache)
        {
            if (context.HttpContext.Response != null)
            {
                if (response.ContentType != null)
                {
                    context.HttpContext.Response.ContentType = response.ContentType;
                }

                // Do set caching headers if instrumentation mode is on
                if (!context.EnableInstrumentation && context.HttpContext.Response.Cache != null)
                {
                    // NOTE: These caching headers were based off of what AssemblyResourceLoader does
                    // TODO: let the bundle change the caching semantics?
                    HttpCachePolicyBase cachePolicy = context.HttpContext.Response.Cache;
                    if (noCache)
                    {
                        cachePolicy.SetCacheability(HttpCacheability.NoCache);
                    }
                    else
                    {
                        cachePolicy.SetCacheability(response.Cacheability);
                        cachePolicy.SetOmitVaryStar(true);
                        cachePolicy.SetExpires(DateTime.Now.AddYears(1));
                        cachePolicy.SetValidUntilExpires(true);
                        cachePolicy.SetLastModified(DateTime.Now);
                        cachePolicy.VaryByHeaders["User-Agent"] = true;
                        // CONSIDER: Last modified logic, need to compute a hash of all the dates/ETag support
                    }
                }
            }
        }
        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);
                }
            }
        }
Example #9
0
        /*public HashSet<string> Endings { get; set; }
         *
         * private bool ContainsEnding(string ending) {
         *  return ending != null && Endings.Contains(ending);
         * }*/

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Duration.TotalMilliseconds <= 0)
            {
                return;
            }

            /* Uri url = filterContext.HttpContext.Request.Url;
             * string localPath = url != null
             *                     ? url.LocalPath.ToLowerInvariant()
             *                     : null;
             * if (string.IsNullOrEmpty(localPath)) {
             *  return;
             * }
             * if (EnumerableValidator.IsNotNullAndNotEmpty(Endings)) {
             *  string fileName = Path.GetFileName(localPath);
             *  string extension = Path.GetExtension(localPath);
             *  if (!ContainsEnding(fileName) && !ContainsEnding(extension)) {
             *      //файл не подходит под искомую маску
             *      return;
             *  }
             *
             *  //файл подошел под искомую маску - установить время кэша
             * }*/

            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(Duration));
            cache.SetMaxAge(Duration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
        }
Example #10
0
        public static AuthorizationContext GetAuthorizationContext(this RequestContext @self, string controllerName, string actionName, RouteValueDictionary routeValues)
        {
            object area;
            string areaName = string.Empty;
            string key      = controllerName + " " + actionName;

            if (routeValues != null && routeValues.TryGetValue("Area", out area))
            {
                areaName = area.ToString();
                key      = areaName + " " + key;
            }

            ClaimsIdentity identity = (ClaimsIdentity)@self.HttpContext.User.Identity;

            HttpCachePolicyBase cachePolicy = @self.HttpContext.Response.Cache;

            //AuthorizationContext authorizationContext = cache.Get(key, () => AuthorizationContextFactory(@self, controllerName, actionName, areaName));
            //if (authorizationContext == null) return null;
            //authorizationContext.RequestContext = @self;
            //authorizationContext.HttpContext = @self.HttpContext;
            //authorizationContext.Result = null;

            //return authorizationContext;

            return(null);
        }
Example #11
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);
        }
        private void SetBundleHeaders(BundleResponse bundleResponse, BundleContext context)
        {
            if (context.HttpContext.Response == null)
            {
                return;
            }

            if (bundleResponse.ContentType != null)
            {
                context.HttpContext.Response.ContentType = bundleResponse.ContentType;
            }

            if (context.EnableInstrumentation || context.HttpContext.Response.Cache == null)
            {
                return;
            }

            HttpCachePolicyBase cache = context.HttpContext.Response.Cache;

            cache.SetCacheability(bundleResponse.Cacheability);
            cache.SetOmitVaryStar(true);
            cache.SetExpires(DateTime.Now.AddYears(1));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(DateTime.Now);
            cache.VaryByHeaders["User-Agent"] = true;
        }
Example #13
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();
        }
Example #14
0
        protected virtual void SetCache(HttpResponseBase response, int cacheDuration, params string[] varyByParams)
        {
            // Cache
            if (cacheDuration > 0)
            {
                DateTime timestamp = DateTime.Now;

                HttpCachePolicyBase cache = response.Cache;
                int duration = cacheDuration;

                cache.SetCacheability(HttpCacheability.Public);
                cache.SetAllowResponseInBrowserHistory(true);
                cache.SetExpires(timestamp.AddSeconds(duration));
                cache.SetMaxAge(new TimeSpan(0, 0, duration));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(timestamp);
                cache.VaryByHeaders["Accept-Encoding"] = true;
                if (varyByParams != null)
                {
                    foreach (var p in varyByParams)
                    {
                        cache.VaryByParams[p] = true;
                    }
                }

                cache.SetOmitVaryStar(true);
                response.AddHeader("Cache-Control", string.Format("public, max-age={0}", cacheDuration));
            }
        }
Example #15
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);
            }
        }
Example #16
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 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);
            }
        }
        protected virtual void HandleAuthorizedRequest(AuthorizationContext filterContext)
        {
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;

            cachePolicy.SetProxyMaxAge(new TimeSpan(0));
            cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
        }
Example #19
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();
                }
            }
        }
Example #20
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);
            //}
        }
Example #21
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")
        }
    }
Example #22
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ClearHeaders();
            response.AppendHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
            response.AppendHeader("Pragma", "no-cache");
            response.AppendHeader("Expires", "-1");
            HttpCachePolicyBase cache = response.Cache;

            cache.SetCacheability(HttpCacheability.NoCache);

            if (string.IsNullOrEmpty(this.Filename))
            {
                this.Filename = "output.xls";
            }
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=" + this.Filename);

            if (this.ContentEncoding == null)
            {
                this.ContentEncoding = System.Text.Encoding.GetEncoding("Shift_JIS");
                //this.ContentEncoding = System.Text.Encoding.UTF8;
            }
            response.ContentEncoding = this.ContentEncoding;

            response.BinaryWrite(Data.GetBuffer());
        }
        /// <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");
            }
        }
Example #24
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);
            }
        }
Example #25
0
        protected void SetClientCacheHeader(DateTime?LastModified, string Etag, HttpCacheability CacheKind, bool ReValidate = true)
        {
            if (!EnableClientCache || LastModified == null && Etag == null)
            {
                return;
            }
            HttpCachePolicyBase cp = Response.Cache;

            cp.AppendCacheExtension("max-age=" + 3600 * MaxClientCacheAgeInHours);
            if (ReValidate)
            {
                cp.AppendCacheExtension("must-revalidate");
                cp.AppendCacheExtension("proxy-revalidate");
            }
            cp.SetCacheability(CacheKind);
            cp.SetOmitVaryStar(false);
            if (LastModified != null)
            {
                cp.SetLastModified(LastModified.Value);
            }
            cp.SetExpires(DateTime.UtcNow.AddHours(MaxClientCacheAgeInHours));
            if (Etag != null)
            {
                cp.SetETag(Etag);
            }
        }
Example #26
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);
            }
        }
Example #27
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);
            }
        }
        /// <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);
            }
        }
Example #29
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);
            }
        }
Example #30
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);
     }
 }
		protected virtual void SetHttpCachePolicy(HttpCachePolicyBase policy)
		{
			policy.SetCacheability(HttpCacheability.Private);
			policy.SetExpires(DateTime.Now.Add(CacheDuration));
			policy.SetMaxAge(CacheDuration);
			policy.SetValidUntilExpires(true);
		}
        internal static void OutputCache(HttpContextBase httpContext,
                                         HttpCachePolicyBase cache,
                                         int numberOfSeconds,
                                         bool sliding,
                                         IEnumerable<string> varyByParams,
                                         IEnumerable<string> varyByHeaders,
                                         IEnumerable<string> varyByContentEncodings,
                                         HttpCacheability cacheability)
        {
            cache.SetCacheability(cacheability);
            cache.SetExpires(httpContext.Timestamp.AddSeconds(numberOfSeconds));
            cache.SetMaxAge(new TimeSpan(0, 0, numberOfSeconds));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(httpContext.Timestamp);
            cache.SetSlidingExpiration(sliding);

            if (varyByParams != null)
            {
                foreach (var p in varyByParams)
                {
                    cache.VaryByParams[p] = true;
                }
            }

            if (varyByHeaders != null)
            {
                foreach (var headerName in varyByHeaders)
                {
                    cache.VaryByHeaders[headerName] = true;
                }
            }

            if (varyByContentEncodings != null)
            {
                foreach (var contentEncoding in varyByContentEncodings)
                {
                    cache.VaryByContentEncodings[contentEncoding] = true;
                }
            }
        }
		protected virtual void SetHttpCachePolicy(HttpCachePolicyBase policy, TemplateInfo info)
		{
			policy.SetCacheability(info.Cacheability);
			policy.SetExpires(DateTime.Now.AddMinutes(info.CacheDuration));
			policy.SetMaxAge(TimeSpan.FromMinutes(info.CacheDuration));
			policy.SetValidUntilExpires(true);
			policy.SetETagFromFileDependencies();
			policy.SetLastModifiedFromFileDependencies();
		}