Created
December 27, 2022 18:36
-
-
Save Lakerfield/0ea3a687974df5192d66a375d78ce0e6 to your computer and use it in GitHub Desktop.
Fix for YARP reverse proxy when using home assistant companion app. Untill https://github.com/microsoft/reverse-proxy/issues/1375 is fixed, this middleware will reject websocket CONNECT over HTTP/2.0
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 Microsoft.AspNetCore.Http.Features; | |
using Microsoft.AspNetCore.Http; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Builder; | |
namespace Lakerfield.Net.ProxyApp.Middleware | |
{ | |
/// <summary> | |
/// Fix to disable websockets over non http/1.1 connections | |
/// Implementation of comment https://github.com/microsoft/reverse-proxy/issues/1375#issuecomment-1312799130 | |
/// </summary> | |
public class RejectWebsocketOverHttp2WhileUnsupportedMiddleware | |
{ | |
private readonly RequestDelegate _next; | |
public RejectWebsocketOverHttp2WhileUnsupportedMiddleware(RequestDelegate next) | |
{ | |
_next = next; | |
} | |
public async Task Invoke(HttpContext context) | |
{ | |
if (context.Request.Method == HttpMethods.Connect && context.Request.Protocol != HttpProtocol.Http11) | |
{ | |
var resetFeature = context.Features.Get<IHttpResetFeature>(); | |
if (resetFeature != null) | |
{ | |
//https://www.rfc-editor.org/rfc/rfc7540#page-51 | |
//HTTP_1_1_REQUIRED (0xd): The endpoint requires that HTTP/1.1 be used instead of HTTP/2. | |
resetFeature.Reset(errorCode: 0xd); | |
return; | |
} | |
} | |
await _next.Invoke(context); | |
} | |
} | |
public static class RejectWebsocketOverHttp2WhileUnsupportedMiddlewareExtensions | |
{ | |
public static IApplicationBuilder UseRejectWebsocketOverHttp2WhileUnsupported(this IApplicationBuilder builder) | |
{ | |
return builder.UseMiddleware<RejectWebsocketOverHttp2WhileUnsupportedMiddleware>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment