private void CheckForAuthFailure(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;
            var response = new HttpResponseWrapper(app.Response);
            var request = new HttpRequestWrapper(app.Request);
            var context = new HttpContextWrapper(app.Context);

            CheckForAuthFailure(request, response, context);
        }
Beispiel #2
1
        public void ProcessRequest(HttpContext context)
        {
            int attachmentID = Convert.ToInt32(context.Request.Params["AttachmentID"]);

            HttpRequestBase request = new HttpRequestWrapper(context.Request);
            HttpResponseBase response = new HttpResponseWrapper(context.Response);

            var uow = ObjectFactory.GetInstance<IUnitOfWork>();
            var attachment = uow.AttachmentRepository.GetQuery().FirstOrDefault(e => e.Id == attachmentID);

            CreateFileResponse(response, attachment);
        }
Beispiel #3
0
        public static string GetIPAddress()
        {

            var wrapper = new HttpRequestWrapper(CurrentHttpContext.Request);

            return ClientIP.ClientIPFromRequest(wrapper, false);
        }
Beispiel #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var request = new HttpRequestWrapper(Page.Request);

            string ipString;
            if (string.IsNullOrEmpty(request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
            {
                ipString = request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                ipString = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
            }

            IPAddress result;
            if (!IPAddress.TryParse(ipString, out result))
            {
                result = IPAddress.None;
            }

            string ip = result.ToString();

            Label1.Text = "Your IP address is: " + ip;

            SetLabel2(ip);
        }
Beispiel #5
0
        /// <summary>
        /// File handler demo for classic Asp.Net or HTML. 
        /// To access it in an Javascript ajax request use: <code>var url = "/Handler/FileHandler.ashx";</code>.
        /// </summary>
        /// <remarks>
        /// NOTE. Edit the web.config file to allow the DELETE method in the system.webServer.handlers section
        /// </remarks>
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            try
            {
                // Wrap the request into a HttpRequestBase type
                HttpRequestBase request = new HttpRequestWrapper(context.Request);


                // Create and initialize the handler
                IFileHandler handler = Backload.FileHandler.Create();
                handler.Init(request);


                // Call the execution pipeline and get the result
                IBackloadResult result = await handler.Execute();


                // Write result to the response and flush
                ResultCreator.Write(context.Response, result);
                context.Response.Flush();

            }
            catch
            {
                context.Response.StatusCode = 500;
            }

        }
		public void Init(HttpApplication context)
		{
			context.BeginRequest += (sender, e) =>
			{
				try
				{
					var application = sender as HttpApplication;
					if (application != null)
					{
						var request = application.Request;
						var response = application.Response;

						if (request != null && response != null)
						{
							var wrappedRequest = new HttpRequestWrapper(request);
							var wrappedResponse = new HttpResponseWrapper(response);

							ResolveDuplicateCookies(wrappedRequest, wrappedResponse);
							Restore(wrappedRequest, wrappedResponse);
						}
					}
				}
				catch
				{
				}
			};
		}
        void AuthenticateScheduler(object sender, EventArgs e)
        {
            var application = (HttpApplication) sender;
            var request = new HttpRequestWrapper(application.Request);
            if (!request.Headers.AllKeys.Contains("x-ms-scheduler-jobid")) return;

            AuthenticateUsingSharedSecret(request);
        }
        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            HttpRequestWrapper wr = new HttpRequestWrapper(Request);
            string userCulture = CultureHelper.GetCurrentCulture(wr, Settings.DefaultCulture);

            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(userCulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(userCulture);
        }
		public void GetPublicFacingUrlSSLForwarder1() {
			HttpRequest req = new HttpRequest("a.aspx", "http://someinternalhost/a.aspx?a=b", "a=b");
			var serverVariables = new NameValueCollection();
			serverVariables["HTTP_X_FORWARDED_PROTO"] = "https";
			serverVariables["HTTP_HOST"] = "somehost";
			Uri actual = new HttpRequestWrapper(req).GetPublicFacingUrl(serverVariables);
			Uri expected = new Uri("https://somehost/a.aspx?a=b");
			Assert.AreEqual(expected, actual);
		}
        void AuthenticateScheduler(object sender, EventArgs e)
        {
            var application = (HttpApplication)sender;
            var request = new HttpRequestWrapper(application.Request);

            // スケジューラからのリクエストか検証
            if (!request.Headers.AllKeys.Contains("x-ms-scheduler-jobid"))
            return;

            // スケジューラからのリクエストの場合は、シークレットキーを認識してRoleを付与
            AuthenticateUsingSharedSecret(request);
        }
        /// <summary>
        /// Handles the PreSendRquestHeaders event of the context control.
        /// </summary>
        void HasSecureAccess(object sender, EventArgs e)
        {
            var httpApplication = (HttpApplication)sender;
            var response = new HttpResponseWrapper(httpApplication.Response);
            var request = new HttpRequestWrapper(httpApplication.Request);
            var context = new HttpContextWrapper(httpApplication.Context);

            if (true.Equals(context.Items["RequestWasNotAuthorized"]) && request.IsAjaxRequest())
            {
                response.StatusCode = 401;
                response.ClearContent();
            }
        }
        private async Task<JQueryFileUpload> HandleRequest()
        {
            var request = new HttpRequestWrapper(HttpContext.Current.Request);
            FileUploadHandler handler = new FileUploadHandler(request, null);       // Get an instance of the handler class
            handler.IncomingRequestStarted += handler_IncomingRequestStarted;       // Register event handler for demo purposes

            var task = handler.HandleRequestAsync();                                // Call the asyncronous handler method
            // Do other stuff here
            var jsonResult = (JsonResult)await task;                                // Awaits the result, but does not block the thread
            //var jsonResult = (JsonResult)await handler.HandleRequestAsync();      // Both methods above can be combined 

            return (JQueryFileUpload)jsonResult.Data;                               // JsonResult.Data is of type object and must be casted 
            // to your plugins handler class
        }
Beispiel #13
0
        private static void OnBeginRequest(object sender, EventArgs e)
        {
            _lastRequestDateTime = DateTime.UtcNow;

            var httpContext = ((HttpApplication)sender).Context;
            var httpRequest = new HttpRequestWrapper(httpContext.Request);

            // HACK: If it's a Razor extension, add a dummy extension to prevent WebPages for blocking it,
            // as we need to serve those files via /vfs
            // Yes, this is an abuse of the trace module
            if (httpRequest.FilePath.IndexOf("vfs/", StringComparison.OrdinalIgnoreCase) >= 0 &&
                (httpRequest.FilePath.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase) ||
                httpRequest.FilePath.EndsWith(".vbhtml", StringComparison.OrdinalIgnoreCase)))
            {
                httpContext.Server.TransferRequest(httpRequest.FilePath + Constants.DummyRazorExtension, preserveForm: true);
                return;
            }

            // Always trace the startup request.
            ITracer tracer = TraceStartup(httpContext);

            // Skip certain paths
            if (TraceExtensions.ShouldSkipRequest(httpRequest))
            {
                TraceServices.RemoveRequestTracer(httpContext);
                return;
            }

            tracer = tracer ?? TraceServices.CreateRequestTracer(httpContext);

            if (tracer == null || tracer.TraceLevel <= TraceLevel.Off)
            {
                return;
            }

            var attribs = GetTraceAttributes(httpContext);

            AddTraceLevel(httpContext, attribs);

            foreach (string key in httpContext.Request.Headers)
            {
                if (!key.Equals("Authorization", StringComparison.OrdinalIgnoreCase) &&
                    !key.Equals("X-MS-CLIENT-PRINCIPAL-NAME", StringComparison.OrdinalIgnoreCase))
                {
                    attribs[key] = httpContext.Request.Headers[key];
                }
            }

            httpContext.Items[_stepKey] = tracer.Step("Incoming Request", attribs);
        }
Beispiel #14
0
		public override async Task ProcessRequestAsync(HttpContext context)
		{
			context.ThrowIfNull("context");

			var request = new HttpRequestWrapper(context.Request);
			var response = new HttpResponseWrapper(context.Response);

			if (_antiCsrfCookieManager != null && _antiCsrfNonceValidator != null && _antiCsrfResponseGenerator != null)
			{
				if (!String.IsNullOrEmpty(context.Request.ContentType))
				{
					try
					{
						var contentType = new ContentType(context.Request.ContentType);

						if (String.Equals(contentType.MediaType, "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) || String.Equals(contentType.MediaType, "multipart/form-data", StringComparison.OrdinalIgnoreCase))
						{
							ValidationResult validationResult = await _antiCsrfNonceValidator.ValidateAsync(request);
							ResponseResult responseResult = await _antiCsrfResponseGenerator.GetResponseAsync(validationResult);

							if (responseResult.ResultType == ResponseResultType.ResponseGenerated)
							{
								await ProcessResponseAsync(context, responseResult.Response, null);
								return;
							}
						}
					}
					catch (FormatException)
					{
					}
				}

				await _antiCsrfCookieManager.ConfigureCookieAsync(request, response);
			}
			{
				IEnumerable<RouteMatchResult> routeMatchResults = await GetRouteMatchResultsAsync(request);
				IEnumerable<Task<ResponseGenerators.ResponseResult>> responseResultTasks = _responseGenerators.Select(arg => arg.GetResponseAsync(new HttpContextWrapper(context), routeMatchResults));

				foreach (Task<ResponseGenerators.ResponseResult> responseResultTask in responseResultTasks)
				{
					ResponseGenerators.ResponseResult responseResult = await responseResultTask;

					if (responseResult.ResultType == ResponseGenerators.ResponseResultType.ResponseGenerated)
					{
						await ProcessResponseAsync(context, await responseResult.Response, responseResult.CacheKey);
						return;
					}
				}
			}
		}
Beispiel #15
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequestBase request = new HttpRequestWrapper(context.Request);      // Wrap the request into a HttpRequestBase type
            context.Response.ContentType = "application/json; charset=utf-8";

            // Important note: we reference the .NET 4.0 assembly here, 
            // not the .NET 4.5 version! If you use the NuGet package, make sure
            // to set the correct reference
            FileUploadHandler handler = new FileUploadHandler(request, null);       // Get an instance of the handler class
            handler.IncomingRequestStarted += handler_IncomingRequestStarted;       // Register event handler for demo purposes

            var jsonResult = (JsonResult)handler.HandleRequest();                   // Call the handler method
            JQueryFileUpload result = (JQueryFileUpload)jsonResult.Data;            // JsonResult.Data is of type object and must be casted 

            context.Response.Write(JsonConvert.SerializeObject(result));            // Serialize the JQueryFileUpload object to a Json string
        }
        private static async void CheckAndPossiblyRefreshToken(ClaimsIdentity id)
        {
            // check if the access token hasn't expired.
            if (DateTime.Now.ToLocalTime() >=
                 (DateTime.Parse(id.FindFirst("expires_at").Value)))
            {
                // expired.  Get a new one.
                var tokenEndpointClient = new OAuth2Client(
                    new Uri(ExpenseTrackerConstants.IdSrvToken),
                    "mvc",
                    "secret");

                var tokenEndpointResponse = 
                    await tokenEndpointClient
                    .RequestRefreshTokenAsync(id.FindFirst("refresh_token").Value);

                if (!tokenEndpointResponse.IsError)
                {
                    // replace the claims with the new values - this means creating a 
                    // new identity!                              
                    var result = from claim in id.Claims
                                 where claim.Type != "access_token" && claim.Type != "refresh_token" &&
                                       claim.Type != "expires_at"
                                 select claim;

                    var claims = result.ToList();

                    claims.Add(new Claim("access_token", tokenEndpointResponse.AccessToken));
                    claims.Add(new Claim("expires_at",
                                 DateTime.Now.AddSeconds(tokenEndpointResponse.ExpiresIn)
                                 .ToLocalTime().ToString()));
                    claims.Add(new Claim("refresh_token", tokenEndpointResponse.RefreshToken));

                    var newIdentity = new ClaimsIdentity(claims, "Cookies");
                    var wrapper = new HttpRequestWrapper(HttpContext.Current.Request);
                    wrapper.GetOwinContext().Authentication.SignIn(newIdentity);
                }
                else
                {
                    // log, ...
                    throw new Exception("An error has occurred");
                }
            }
             

           
        }
 public static void UpdateStatusCodeForFailedAuthentication() {
     HttpContext httpContext = HttpContext.Current;
     if (httpContext != null &&
         httpContext.Response.StatusCode == (int)HttpStatusCode.Found) {
         HttpRequestWrapper request = new HttpRequestWrapper(httpContext.Request);
         if (!request.IsBrowserRequest()) {
             httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
             httpContext.Response.ClearContent();
             try {
                 if (httpContext.Response.Headers.AllKeys.Contains("Location")) {
                     httpContext.Response.Headers.Remove("Location");
                 }
             }
             catch (PlatformNotSupportedException) {
                 // We need IIS 7 integrated mode to remove the header.  Just swallow the exception if
                 // we can't remove the header.
             }
         }
     }
 }
Beispiel #18
0
        public void ProcessRequest(HttpContext context)
        {
            context.ThrowIfNull("context");

            var request = new HttpRequestWrapper(context.Request);
            var response = new HttpResponseWrapper(context.Response);
            // ReSharper disable ImplicitlyCapturedClosure
            RouteMatchResult[] routeMatchResults = _routes.Select(arg => new RouteMatchResult(arg, arg.MatchesRequest(request))).ToArray();
            // ReSharper restore ImplicitlyCapturedClosure
            ResponseResult responseResult = _responseGenerators
                .Select(arg => arg.GetResponse(request, routeMatchResults))
                .FirstOrDefault(arg => arg.ResultType != ResponseResultType.ResponseNotGenerated);

            if (responseResult == null)
            {
                throw new ApplicationException("No response was generated.");
            }

            ProcessResponse(request, response, responseResult.Response, responseResult.CacheKey);
        }
Beispiel #19
0
 public override string GetVaryByCustomString(HttpContext context, string custom)
 {
     var customs = custom.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
     var cacheKey = string.Empty;
     foreach (var type in customs)
     {
         switch (type)
         {
             case VaryByCustom.User:
                 cacheKey += "ByUser_" + (context.User.Identity.IsAuthenticated ? context.User.Identity.Name : string.Empty);
                 break;
             case VaryByCustom.UserIsAuthenticated:
                 cacheKey += "ByUserIsAuthenticated_" + (context.User.Identity.IsAuthenticated ? "user" : "anon");
                 break;
             case VaryByCustom.Ajax:
                 var requestBase = new HttpRequestWrapper(context.Request);
                 cacheKey += "ByAjax_" + requestBase.IsAjaxRequest();
                 break;
         }
     }
     return cacheKey;
 }
    protected void btnJoingChat_Click(object sender, EventArgs e)
    {
        var existclient = UsersModels.isUserExist(new HttpRequestWrapper(this.Request));

        if (existclient == false)
        {

            var request = new HttpRequestWrapper(this.Request);

            string ID = UsersModels.Instance.ClientID();
            Dictionary<string, object> meta = new Dictionary<string, object>();
            meta.Add("username", request.Form["username"].ToString());
            meta.Add("ID", ID.ToString());
            meta.Add("status", global::Users.isOnline.online.ToString());

            ClientInfo = string.Format(@"data-clientinfo='{0}'", JsonConvert.SerializeObject(meta, Formatting.Indented).ToString());

            IsUserAuthenticated = true;
            signin.Visible = false;
            messageboard.Visible = true;
        }
    }
Beispiel #21
0
        private static void OnBeginRequest(object sender, EventArgs e)
        {
            _lastRequestDateTime = DateTime.UtcNow;

            var httpContext = ((HttpApplication)sender).Context;
            var httpRequest = new HttpRequestWrapper(httpContext.Request);

            // Always trace the startup request.
            ITracer tracer = TraceStartup(httpContext);

            // Skip certain paths
            if (TraceExtensions.ShouldSkipRequest(httpRequest))
            {
                TraceServices.RemoveRequestTracer(httpContext);
                return;
            }

            tracer = tracer ?? TraceServices.CreateRequestTracer(httpContext);

            if (tracer == null || tracer.TraceLevel <= TraceLevel.Off)
            {
                return;
            }

            var attribs = GetTraceAttributes(httpContext);

            AddTraceLevel(httpContext, attribs);

            foreach (string key in httpContext.Request.Headers)
            {
                if (!key.Equals("Authorization", StringComparison.OrdinalIgnoreCase))
                {
                    attribs[key] = httpContext.Request.Headers[key];
                }
            }

            httpContext.Items[_stepKey] = tracer.Step("Incoming Request", attribs);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var skipSessionExpirationCheck = filterContext.ActionDescriptor.IsDefined(typeof(IgnoreSessionExpireAttribute), true)
                                        || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(IgnoreSessionExpireAttribute), true);

            if (!skipSessionExpirationCheck)
            {
                HttpContext currentContext = HttpContext.Current;

                // check if session is supported
                if (currentContext.Session != null)
                {
                    // check if a new session id was generated
                    if (currentContext.Session.IsNewSession)
                    {
                        // If it says it is a new session, but an existing cookie exists, then it must have timed out
                        string sessionCookie = currentContext.Request.Headers["Cookie"];

                        if (sessionCookie != null && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                        {
                            var req = new HttpRequestWrapper(System.Web.HttpContext.Current.Request);
                            if (req.IsAjaxRequest())
                            {
                                //do nothing as it is being handled in relevant ajax calls
                            }
                            else
                            {
                                //we can specify which action to be called in case session has expired
                                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "Controller", "ControllerName" }, { "Action", "ActionName" } });
                            }

                        }
                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }
Beispiel #23
0
        void context_BeginRequest(object sender, EventArgs e)
        {
            var request = new HttpRequestWrapper(HttpContext.Current.Request);

            if (request.HttpMethod.ToLowerInvariant() != "get")
            {
                return;
            }

            if (HasUpperCaseLetters(request.RawUrl))
            {
                RedirectToLowerCaseVersion(request.RawUrl, new HttpResponseWrapper(HttpContext.Current.Response));
                return;
            }

            if (_redirects.Any(x => x.Match(request)))
            {
                UrlRedirect redirect = _redirects.First(x => x.Match(request));
                var response = new HttpResponseWrapper(HttpContext.Current.Response);
                redirect.Redirect(request, response);
                return;
            }
        }
		/// <summary>
		/// Creates the authentication requests for a given user-supplied Identifier.
		/// </summary>
		/// <param name="identifier">The identifier to create a request for.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// A sequence of authentication requests, any one of which may be
		/// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier" />.
		/// </returns>
		private async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsCoreAsync(Identifier identifier, CancellationToken cancellationToken) {
			ErrorUtilities.VerifyArgumentNotNull(identifier, "identifier"); // NO CODE CONTRACTS! (yield return used here)
			IEnumerable<IAuthenticationRequest> requests;
			var requestContext = new HttpRequestWrapper(this.Context.Request);
			var results = new List<IAuthenticationRequest>();

			// Approximate the returnTo (either based on the customize property or the page URL)
			// so we can use it to help with Realm resolution.
			Uri returnToApproximation;
			if (this.ReturnToUrl != null) {
				string returnToResolvedPath = this.ResolveUrl(this.ReturnToUrl);
				returnToApproximation = new Uri(requestContext.GetPublicFacingUrl(), returnToResolvedPath);
			} else {
				returnToApproximation = this.Page.Request.Url;
			}

			// Resolve the trust root, and swap out the scheme and port if necessary to match the
			// return_to URL, since this match is required by OpenID, and the consumer app
			// may be using HTTP at some times and HTTPS at others.
			UriBuilder realm = OpenIdUtilities.GetResolvedRealm(this.Page, this.RealmUrl, requestContext);
			realm.Scheme = returnToApproximation.Scheme;
			realm.Port = returnToApproximation.Port;

			// Initiate OpenID request
			// We use TryParse here to avoid throwing an exception which 
			// might slip through our validator control if it is disabled.
			Realm typedRealm = new Realm(realm);
			if (string.IsNullOrEmpty(this.ReturnToUrl)) {
				requests = await this.RelyingParty.CreateRequestsAsync(identifier, typedRealm, requestContext);
			} else {
				// Since the user actually gave us a return_to value,
				// the "approximation" is exactly what we want.
				requests = await this.RelyingParty.CreateRequestsAsync(identifier, typedRealm, returnToApproximation, cancellationToken);
			}

			// Some OPs may be listed multiple times (one with HTTPS and the other with HTTP, for example).
			// Since we're gathering OPs to try one after the other, just take the first choice of each OP
			// and don't try it multiple times.
			requests = requests.Distinct(DuplicateRequestedHostsComparer.Instance);

			// Configure each generated request.
			foreach (var req in requests) {
				if (this.IsPopupAppropriate(req)) {
					// Inform ourselves in return_to that we're in a popup.
					req.SetUntrustedCallbackArgument(UIPopupCallbackKey, "1");

					if (req.DiscoveryResult.IsExtensionSupported<UIRequest>()) {
						// Inform the OP that we'll be using a popup window consistent with the UI extension.
						// But beware that the extension MAY have already been added if we're using
						// the OpenIdAjaxRelyingParty class.
						if (!((AuthenticationRequest)req).Extensions.OfType<UIRequest>().Any()) {
							req.AddExtension(new UIRequest());
						}

						// Provide a hint for the client javascript about whether the OP supports the UI extension.
						// This is so the window can be made the correct size for the extension.
						// If the OP doesn't advertise support for the extension, the javascript will use
						// a bigger popup window.
						req.SetUntrustedCallbackArgument(PopupUISupportedJSHint, "1");
					}
				}

				// Add the extensions injected into the control.
				foreach (var extension in this.Extensions) {
					req.AddExtension(extension);
				}

				// Add state that needs to survive across the redirect, but at this point
				// only save those properties that are not expected to be changed by a
				// LoggingIn event handler.
				req.SetUntrustedCallbackArgument(ReturnToReceivingControlId, this.ClientID);

				// Apply the control's association preference to this auth request, but only if
				// it is less demanding (greater ordinal value) than the existing one.
				// That way, we protect against retrying an association that was already attempted.
				var authReq = (AuthenticationRequest)req;
				if (authReq.AssociationPreference < this.AssociationPreference) {
					authReq.AssociationPreference = this.AssociationPreference;
				}

				if (this.OnLoggingIn(req)) {
					// We save this property after firing OnLoggingIn so that the host page can
					// change its value and have that value saved.
					req.SetUntrustedCallbackArgument(UsePersistentCookieCallbackKey, this.UsePersistentCookie.ToString());

					results.Add(req);
				}
			}

			return results;
		}
Beispiel #25
0
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            using (_tracer.Step("FetchHandler"))
            {
                // Redirect GET /deploy requests to the Kudu root for convenience when using URL from Azure portal
                if (String.Equals(context.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                {
                    context.Response.Redirect("~/");
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                if (!String.Equals(context.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                context.Response.TrySkipIisCustomErrors = true;

                DeploymentInfo deployInfo = null;

                // We are going to assume that the branch details are already set by the time it gets here. This is particularly important in the mercurial case,
                // since Settings hardcodes the default value for Branch to be "master". Consequently, Kudu will NoOp requests for Mercurial commits.
                string targetBranch = _settings.GetBranch();
                try
                {
                    var request = new HttpRequestWrapper(context.Request);
                    JObject payload = GetPayload(request);
                    DeployAction action = GetRepositoryInfo(request, payload, targetBranch, out deployInfo);
                    if (action == DeployAction.NoOp)
                    {
                        return;
                    }

                    // If Scm is not enabled, we will reject all but one payload for GenericHandler
                    // This is to block the unintended CI with Scm providers like GitHub
                    // Since Generic payload can only be done by user action, we loosely allow
                    // that and assume users know what they are doing.  Same applies to git
                    // push/clone endpoint.
                    if (!_settings.IsScmEnabled() && !(deployInfo.Handler is GenericHandler || deployInfo.Handler is DropboxHandler))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }
                }
                catch (FormatException ex)
                {
                    _tracer.TraceError(ex);
                    context.Response.StatusCode = 400;
                    context.Response.Write(ex.Message);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                // for CI payload, we will return Accepted and do the task in the BG
                // if isAsync is defined, we will return Accepted and do the task in the BG
                // since autoSwap relies on the response header, deployment has to be synchronously.
                bool isAsync = String.Equals(context.Request.QueryString["isAsync"], "true", StringComparison.OrdinalIgnoreCase);
                bool isBackground = isAsync || deployInfo.IsContinuous;
                if (isBackground)
                {
                    using (_tracer.Step("Start deployment in the background"))
                    {
                        ChangeSet tempChangeSet = null;
                        IDisposable tempDeployment = null;
                        if (isAsync)
                        {
                            // create temporary deployment before the actual deployment item started
                            // this allows portal ui to readily display on-going deployment (not having to wait for fetch to complete).
                            // in addition, it captures any failure that may occur before the actual deployment item started
                            tempDeployment = _deploymentManager.CreateTemporaryDeployment(
                                                            Resources.ReceivingChanges,
                                                            out tempChangeSet,
                                                            deployInfo.TargetChangeset,
                                                            deployInfo.Deployer);
                        }

                        PerformBackgroundDeployment(deployInfo, _environment, _settings, _tracer.TraceLevel, context.Request.Url, tempDeployment, _autoSwapHandler, tempChangeSet);
                    }

                    // to avoid regression, only set location header if isAsync
                    if (isAsync)
                    {
                        // latest deployment keyword reserved to poll till deployment done
                        context.Response.Headers["Location"] = new Uri(context.Request.Url,
                            String.Format("/api/deployments/{0}?deployer={1}&time={2}", Constants.LatestDeployment, deployInfo.Deployer, DateTime.UtcNow.ToString("yyy-MM-dd_HH-mm-ssZ"))).ToString();
                    }
                    context.Response.StatusCode = (int)HttpStatusCode.Accepted;
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                _tracer.Trace("Attempting to fetch target branch {0}", targetBranch);
                bool acquired = await _deploymentLock.TryLockOperationAsync(async () =>
                {
                    if (_autoSwapHandler.IsAutoSwapOngoing())
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Conflict;
                        context.Response.Write(Resources.Error_AutoSwapDeploymentOngoing);
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }

                    await PerformDeployment(deployInfo);
                }, TimeSpan.Zero);

                if (!acquired)
                {
                    // Create a marker file that indicates if there's another deployment to pull
                    // because there was a deployment in progress.
                    using (_tracer.Step("Update pending deployment marker file"))
                    {
                        // REVIEW: This makes the assumption that the repository url is the same.
                        // If it isn't the result would be buggy either way.
                        FileSystemHelpers.SetLastWriteTimeUtc(_markerFilePath, DateTime.UtcNow);
                    }

                    // Return a http 202: the request has been accepted for processing, but the processing has not been completed.
                    context.Response.StatusCode = (int)HttpStatusCode.Accepted;
                    context.ApplicationInstance.CompleteRequest();
                }
            }
        }
Beispiel #26
0
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            using (_tracer.Step("FetchHandler"))
            {
                // Redirect GET /deploy requests to the Kudu root for convenience when using URL from Azure portal
                if (String.Equals(context.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                {
                    context.Response.Redirect("~/");
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                if (!String.Equals(context.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                context.Response.TrySkipIisCustomErrors = true;

                DeploymentInfo deployInfo = null;

                // We are going to assume that the branch details are already set by the time it gets here. This is particularly important in the mercurial case,
                // since Settings hardcodes the default value for Branch to be "master". Consequently, Kudu will NoOp requests for Mercurial commits.
                string targetBranch = _settings.GetBranch();
                try
                {
                    var request = new HttpRequestWrapper(context.Request);
                    JObject payload = GetPayload(request);
                    DeployAction action = GetRepositoryInfo(request, payload, targetBranch, out deployInfo);
                    if (action == DeployAction.NoOp)
                    {
                        return;
                    }

                    // If Scm is not enabled, we will reject all but one payload for GenericHandler
                    // This is to block the unintended CI with Scm providers like GitHub
                    // Since Generic payload can only be done by user action, we loosely allow
                    // that and assume users know what they are doing.  Same applies to git
                    // push/clone endpoint.
                    if (!_settings.IsScmEnabled() && !(deployInfo.Handler is GenericHandler || deployInfo.Handler is DropboxHandler))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }
                }
                catch (FormatException ex)
                {
                    _tracer.TraceError(ex);
                    context.Response.StatusCode = 400;
                    context.Response.Write(ex.Message);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                _tracer.Trace("Attempting to fetch target branch {0}", targetBranch);
                bool acquired = await _deploymentLock.TryLockOperationAsync(async () =>
                {
                    if (_autoSwapHandler.IsAutoSwapOngoing())
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Conflict;
                        context.Response.Write(Resources.Error_AutoSwapDeploymentOngoing);
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }

                    await PerformDeployment(deployInfo);

                    _autoSwapHandler.HandleAutoSwap(verifyActiveDeploymentIdChanged: false);
                }, TimeSpan.Zero);

                if (!acquired)
                {
                    // Create a marker file that indicates if there's another deployment to pull
                    // because there was a deployment in progress.
                    using (_tracer.Step("Update pending deployment marker file"))
                    {
                        // REVIEW: This makes the assumption that the repository url is the same.
                        // If it isn't the result would be buggy either way.
                        FileSystemHelpers.SetLastWriteTimeUtc(_markerFilePath, DateTime.UtcNow);
                    }

                    // Return a http 202: the request has been accepted for processing, but the processing has not been completed.
                    context.Response.StatusCode = (int)HttpStatusCode.Accepted;
                    context.ApplicationInstance.CompleteRequest();
                }
            }
        }
Beispiel #27
0
		public HttpContextStub5 (string requestUrl, string path, string appPath)
			: base (requestUrl, path, appPath)
		{
			wrapper = new FakeHttpRequestWrapper (requestUrl, path, appPath);
		}
Beispiel #28
0
		public HttpContextStub4 (string requestUrl, string path, string appPath, bool supportHandler)
			: base (requestUrl, path, appPath, supportHandler)
		{
			wrapper = new FakeHttpRequestWrapper (requestUrl, path, appPath);
		}
Beispiel #29
0
        private static void OnBeginRequest(object sender, EventArgs e)
        {
            _lastRequestDateTime = DateTime.UtcNow;

            var httpContext = ((HttpApplication)sender).Context;
            var httpRequest = new HttpRequestWrapper(httpContext.Request);

            // HACK: This is abusing the trace module
            // Disallow GET requests from CSM extensions bridge
            // Except if owner or coadmin (aka legacy or non-rbac) authorization
            if (!String.IsNullOrEmpty(httpRequest.Headers["X-MS-VIA-EXTENSIONS-ROUTE"]) &&
                httpRequest.HttpMethod.Equals(HttpMethod.Get.Method, StringComparison.OrdinalIgnoreCase) &&
                !String.Equals(httpRequest.Headers["X-MS-CLIENT-AUTHORIZATION-SOURCE"], "legacy", StringComparison.OrdinalIgnoreCase) &&
                !IsRbacWhiteListPaths(httpRequest.Url.AbsolutePath))
            {
                httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                httpContext.Response.End();
            }

            TryConvertSpecialHeadersToEnvironmentVariable(httpRequest);

            // HACK: If it's a Razor extension, add a dummy extension to prevent WebPages for blocking it,
            // as we need to serve those files via /vfs
            // Yes, this is an abuse of the trace module
            if (httpRequest.FilePath.IndexOf("vfs/", StringComparison.OrdinalIgnoreCase) >= 0 &&
                (httpRequest.FilePath.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase) ||
                httpRequest.FilePath.EndsWith(".vbhtml", StringComparison.OrdinalIgnoreCase)))
            {
                httpContext.Server.TransferRequest(httpRequest.FilePath + Constants.DummyRazorExtension, preserveForm: true);
                return;
            }

            // Always trace the startup request.
            ITracer tracer = TraceStartup(httpContext);

            // Skip certain paths
            if (TraceExtensions.ShouldSkipRequest(httpRequest))
            {
                TraceServices.RemoveRequestTracer(httpContext);
                return;
            }

            tracer = tracer ?? TraceServices.CreateRequestTracer(httpContext);

            if (tracer == null || tracer.TraceLevel <= TraceLevel.Off)
            {
                return;
            }

            var attribs = GetTraceAttributes(httpContext);

            AddTraceLevel(httpContext, attribs);

            foreach (string key in httpContext.Request.Headers)
            {
                if (!key.Equals("Authorization", StringComparison.OrdinalIgnoreCase) &&
                    !key.Equals("X-MS-CLIENT-PRINCIPAL-NAME", StringComparison.OrdinalIgnoreCase))
                {
                    attribs[key] = httpContext.Request.Headers[key];
                }
            }

            httpContext.Items[_stepKey] = tracer.Step(XmlTracer.IncomingRequestTrace, attribs);
        }
 public override void Execute(IHttpRequest request, IHttpResponse response, object requestDto) {
     try {
         var authServerKeys = AppHostBase.Instance.Container.ResolveNamed<ICryptoKeyPair>("authServer");
         var dataServerKeys = AppHostBase.Instance.Container.ResolveNamed<ICryptoKeyPair>("dataServer");
         var tokenAnalyzer = new StandardAccessTokenAnalyzer(authServerKeys.PublicSigningKey, dataServerKeys.PrivateEncryptionKey);
         var oauth2ResourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(tokenAnalyzer);
         var wrappedRequest = new HttpRequestWrapper((HttpRequest)request.OriginalRequest);
         HttpContext.Current.User = oauth2ResourceServer.GetPrincipal(wrappedRequest, oauth2Scopes);
     } catch (ProtocolFaultResponseException x) {
         HandleOAuth2Exception(request, response, x);
     }
 }