Skip to content

Instantly share code, notes, and snippets.

@tpeczek
Created September 7, 2017 19:10
Show Gist options
  • Save tpeczek/8ad871cc9c286d9d8f4f89270265b4cd to your computer and use it in GitHub Desktop.
Save tpeczek/8ad871cc9c286d9d8f4f89270265b4cd to your computer and use it in GitHub Desktop.
ASP.NET Core middleware for SSL Acceleration (Offloading) support
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));
}
}
}
@tpeczek
Copy link
Author

tpeczek commented Apr 14, 2018

@AnkurMadaan
Copy link

What is the best place to put this middleware and do i need UseHttpsRedirection() along with this? Please suggest.

@tpeczek
Copy link
Author

tpeczek commented Sep 11, 2020

@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