예제 #1
0
        public async Task Should_match_rule()
        {
            var matched = false;

            _rules.Add(new ProxyRule {
                Matcher  = uri => uri.AbsolutePath.Contains("api"),
                Modifier = (msg, user) => { matched = true; }
            });
            await _proxy.Invoke(_context);

            Assert.IsTrue(matched);
        }
예제 #2
0
        /// <summary>
        /// The invoke method is called by the ProxyExtension class
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                string requestPath = context.Request.Path.Value;
                _logger.LogInformation("Api Path: " + requestPath);

                // set http security headers
                if (requestPath.Contains("/fonts") ||
                    requestPath.Contains("/images"))
                {
                    context.Response.Headers[HeaderNames.CacheControl] = "private, max-age=60";
                    context.Response.Headers[HeaderNames.Expires]      = "60";
                }
                else
                {
                    context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate, private";
                    context.Response.Headers[HeaderNames.Pragma]       = "no-cache";
                    context.Response.Headers[HeaderNames.Expires]      = "-1";
                }

                context.Response.Headers["X-Frame-Options"]        = "SAMEORIGIN";
                context.Response.Headers["X-XSS-Protection"]       = "1; mode=block";
                context.Response.Headers["X-Content-Type-Options"] = "nosniff";

                await _proxy.Invoke(context);
            }
            catch (Exception e)
            {
                _logger.LogError(new EventId(-1, "ApiProxyMiddleware Exception"), e, $"An unexpected exception occured while forwarding a request to the API proxy; {_apiUri}.");
                context.Response.StatusCode  = (int)System.Net.HttpStatusCode.NotFound;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync($"Exception encountered forwarding a request to {_apiUri}.");
            }
        }
예제 #3
0
        /// <summary>
        /// The invoke method is called by the ProxyExtension class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                string requestPath = context.Request.Path.Value;
                int    indexOfApi  = requestPath.IndexOf(_pathKey);
                context.Request.Path = requestPath.Remove(0, indexOfApi);

                // Set security headers
                context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate, private";
                context.Response.Headers[HeaderNames.Pragma]       = "no-cache";
                context.Response.Headers["X-Frame-Options"]        = "SAMEORIGIN";
                context.Response.Headers["X-XSS-Protection"]       = "1; mode=block";
                context.Response.Headers["X-Content-Type-Options"] = "nosniff";

                await _proxy.Invoke(context);
            }
            catch (Exception e)
            {
                _logger.LogError(new EventId(-1, "ProxyMiddleware Exception"), e, $"An unexpected exception occured while forwarding a request to the proxy; {_apiUri}.");
                context.Response.StatusCode  = (int)System.Net.HttpStatusCode.NotFound;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync($"Exception encountered forwarding a request to {_apiUri}.");
            }
        }
예제 #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseStaticFiles();

            // For any requests coming in from '/dist/**/*' or '__webpack_hmr', we wan't to proxy those requests
            // to our webpack dev server that is running.
            // Make sure you have 'gulp dev-server' running before starting the .NET web stuff.
            // NOTE: You may want to configure this to only run on a dev environment, and not production.
            var proxyOptions = new OptionsWrapper <ProxyOptions>(new ProxyOptions
            {
                Host = "localhost",
                Port = "5001"
            });

            app.Use(async(context, next) =>
            {
                if (!context.Request.Path.StartsWithSegments("/dist") &&
                    !context.Request.Path.StartsWithSegments("/__webpack_hmr"))
                {
                    await next();
                    return;
                }
                var proxyMiddleware = new ProxyMiddleware(httpContext => next.Invoke(), proxyOptions);
                await proxyMiddleware.Invoke(context);
            });

            app.UseJsEngine(); // this needs to be before MVC

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public void UsesProxy()
        {
            const string ENDPOINT = "http://foobar.com/v1";

            // Arrange
            var next  = new Mock <RequestDelegate>();
            var proxy = new Mock <IProxy>();
            var log   = new Mock <ILogger <ProxyMiddleware> >();

            var config = new Mock <IConfig>();
            // config.SetupGet(x => x.Endpoint).Returns(ENDPOINT);

            var request  = new Mock <HttpRequest>();
            var response = new Mock <HttpResponse>();
            var context  = new Mock <HttpContext>();

            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.Response).Returns(response.Object);

            var target = new ProxyMiddleware(next.Object, config.Object, proxy.Object, log.Object);

            // Act
            target.Invoke(context.Object).Wait();

            // Assert
            proxy.Verify(x => x.ProcessAsync(request.Object, response.Object), Times.Once);
        }