Repository: andychiare/netcore2-reverse-proxy Branch: master Commit: 197d20144220 Files: 10 Total size: 11.8 KB Directory structure: gitextract_a85h9ktw/ ├── .gitignore ├── LICENSE ├── README.md ├── ReverseProxyApplication/ │ ├── Program.cs │ ├── Properties/ │ │ └── launchSettings.json │ ├── ReverseProxyApplication.csproj │ ├── ReverseProxyApplication.csproj.user │ ├── ReverseProxyMiddleware.cs │ └── Startup.cs └── ReverseProxyApplication.sln ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /ReverseProxyApplication/bin /ReverseProxyApplication/obj ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Andrea Chiarelli Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # netcore2-reverse-proxy This is a .NET Core 2 sample project showing how to implement a custom reverse proxy, as described in the article [Building a Reverse Proxy in .NET Core](https://auth0.com/blog/building-a-reverse-proxy-in-dot-net-core/). ## Running the project ## You can run the Web application from Visual Studio or by typing `dotnet run` in a command window. When the application is running, you can point your browser to `localhost:5001` and access a Google form without leaving the `localhost` domain. ================================================ FILE: ReverseProxyApplication/Program.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ReverseProxyApplication { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup(); } } ================================================ FILE: ReverseProxyApplication/Properties/launchSettings.json ================================================ { "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:57068", "sslPort": 44388 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "ReverseProxyApplication": { "commandName": "Project", "launchBrowser": true, "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ================================================ FILE: ReverseProxyApplication/ReverseProxyApplication.csproj ================================================ netcoreapp2.1 ================================================ FILE: ReverseProxyApplication/ReverseProxyApplication.csproj.user ================================================  ProjectDebugger ReverseProxyApplication ================================================ FILE: ReverseProxyApplication/ReverseProxyMiddleware.cs ================================================ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace ReverseProxyApplication { public class ReverseProxyMiddleware { private static readonly HttpClient _httpClient = new HttpClient(); private readonly RequestDelegate _nextMiddleware; public ReverseProxyMiddleware(RequestDelegate nextMiddleware) { _nextMiddleware = nextMiddleware; } public async Task Invoke(HttpContext context) { var targetUri = BuildTargetUri(context.Request); if (targetUri != null) { var targetRequestMessage = CreateTargetMessage(context, targetUri); using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted)) { context.Response.StatusCode = (int)responseMessage.StatusCode; CopyFromTargetResponseHeaders(context, responseMessage); await ProcessResponseContent(context, responseMessage); } return; } await _nextMiddleware(context); } private async Task ProcessResponseContent(HttpContext context, HttpResponseMessage responseMessage) { var content = await responseMessage.Content.ReadAsByteArrayAsync(); if (IsContentOfType(responseMessage, "text/html") || IsContentOfType(responseMessage, "text/javascript")) { var stringContent = Encoding.UTF8.GetString(content); var newContent = stringContent.Replace("https://www.google.com", "/google") .Replace("https://www.gstatic.com", "/googlestatic") .Replace("https://docs.google.com/forms", "/googleforms"); await context.Response.WriteAsync(newContent, Encoding.UTF8); } else { await context.Response.Body.WriteAsync(content); } } private bool IsContentOfType(HttpResponseMessage responseMessage, string type) { var result = false; if (responseMessage.Content?.Headers?.ContentType != null) { result = responseMessage.Content.Headers.ContentType.MediaType == type; } return result; } private HttpRequestMessage CreateTargetMessage(HttpContext context, Uri targetUri) { var requestMessage = new HttpRequestMessage(); CopyFromOriginalRequestContentAndHeaders(context, requestMessage); targetUri = new Uri(QueryHelpers.AddQueryString(targetUri.OriginalString, new Dictionary() { { "entry.1884265043", "John Doe" }})); requestMessage.RequestUri = targetUri; requestMessage.Headers.Host = targetUri.Host; requestMessage.Method = GetMethod(context.Request.Method); return requestMessage; } private void CopyFromOriginalRequestContentAndHeaders(HttpContext context, HttpRequestMessage requestMessage) { var requestMethod = context.Request.Method; if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) && !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod)) { var streamContent = new StreamContent(context.Request.Body); requestMessage.Content = streamContent; } foreach (var header in context.Request.Headers) { requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()); } } private void CopyFromTargetResponseHeaders(HttpContext context, HttpResponseMessage responseMessage) { foreach (var header in responseMessage.Headers) { context.Response.Headers[header.Key] = header.Value.ToArray(); } foreach (var header in responseMessage.Content.Headers) { context.Response.Headers[header.Key] = header.Value.ToArray(); } context.Response.Headers.Remove("transfer-encoding"); } private static HttpMethod GetMethod(string method) { if (HttpMethods.IsDelete(method)) return HttpMethod.Delete; if (HttpMethods.IsGet(method)) return HttpMethod.Get; if (HttpMethods.IsHead(method)) return HttpMethod.Head; if (HttpMethods.IsOptions(method)) return HttpMethod.Options; if (HttpMethods.IsPost(method)) return HttpMethod.Post; if (HttpMethods.IsPut(method)) return HttpMethod.Put; if (HttpMethods.IsTrace(method)) return HttpMethod.Trace; return new HttpMethod(method); } private Uri BuildTargetUri(HttpRequest request) { Uri targetUri = null; PathString remainingPath; if (request.Path.StartsWithSegments("/googleforms", out remainingPath)) { targetUri = new Uri("https://docs.google.com/forms" + remainingPath); } if (request.Path.StartsWithSegments("/google", out remainingPath)) { targetUri = new Uri("https://www.google.com" + remainingPath); } if (request.Path.StartsWithSegments("/googlestatic", out remainingPath)) { targetUri = new Uri(" https://www.gstatic.com" + remainingPath); } return targetUri; } } } ================================================ FILE: ReverseProxyApplication/Startup.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace ReverseProxyApplication { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMiddleware(); app.Run(async (context) => { await context.Response.WriteAsync("Register to receive a T-shirt"); }); } } } ================================================ FILE: ReverseProxyApplication.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.28307.136 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReverseProxyApplication", "ReverseProxyApplication\ReverseProxyApplication.csproj", "{58B4515A-294E-4C42-A583-77EC95AFF5DA}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {58B4515A-294E-4C42-A583-77EC95AFF5DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {58B4515A-294E-4C42-A583-77EC95AFF5DA}.Debug|Any CPU.Build.0 = Debug|Any CPU {58B4515A-294E-4C42-A583-77EC95AFF5DA}.Release|Any CPU.ActiveCfg = Release|Any CPU {58B4515A-294E-4C42-A583-77EC95AFF5DA}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {CE1981AA-AB03-4074-B464-1A50E3CF42DE} EndGlobalSection EndGlobal