Created
September 7, 2017 19:10
-
-
Save tpeczek/8ad871cc9c286d9d8f4f89270265b4cd to your computer and use it in GitHub Desktop.
ASP.NET Core middleware for SSL Acceleration (Offloading) support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.Http.Features; | |
using Microsoft.Extensions.Options; | |
namespace Demo.AspNetCore.SslAcceleration.Middlewares | |
{ | |
public class SslAccelerationOptions | |
{ | |
public string HeaderName { get; set; } | |
public string HeaderValue { get; set; } | |
} | |
public class SslAccelerationMiddleware | |
{ | |
private const string HTTPS_SCHEME = "https"; | |
private readonly RequestDelegate _next; | |
private readonly SslAccelerationOptions _options; | |
public SslAccelerationMiddleware(RequestDelegate next, IOptions<SslAccelerationOptions> options) | |
{ | |
_next = next ?? throw new ArgumentNullException(nameof(next)); | |
_options = options?.Value ?? throw new ArgumentNullException(nameof(options)); | |
} | |
public Task Invoke(HttpContext context) | |
{ | |
if (!context.Request.IsHttps) | |
{ | |
if (context.Request.Headers.ContainsKey(_options.HeaderName) && context.Request.Headers[_options.HeaderName].Equals(_options.HeaderValue)) | |
{ | |
IHttpRequestFeature httpRequestFeature = context.Features.Get<IHttpRequestFeature>(); | |
httpRequestFeature.Scheme = HTTPS_SCHEME; | |
} | |
} | |
return _next(context); | |
} | |
} | |
public static class SslAccelerationMiddlewareExtensions | |
{ | |
public static IApplicationBuilder UseSslAcceleration(this IApplicationBuilder app) | |
{ | |
if (app == null) | |
{ | |
throw new ArgumentNullException(nameof(app)); | |
} | |
return app.UseMiddleware<SslAccelerationMiddleware>(); | |
} | |
public static IApplicationBuilder UseSslAcceleration(this IApplicationBuilder app, SslAccelerationOptions options) | |
{ | |
if (app == null) | |
{ | |
throw new ArgumentNullException(nameof(app)); | |
} | |
if (options == null) | |
{ | |
throw new ArgumentNullException(nameof(options)); | |
} | |
return app.UseMiddleware<SslAccelerationMiddleware>(Options.Create(options)); | |
} | |
} | |
} |
What is the best place to put this middleware and do i need UseHttpsRedirection() along with this? Please suggest.
@AnkurMadaan I would suggest placing this middleware as early in pipeline as possible. When it comes to UseHttpsRedirection()
, it is not required, it's usage depends if you want to support both HTTP and HTTPS requests or not.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Description --> https://www.tpeczek.com/2017/09/supporting-ssl-acceleration-offloading.html