aspnetcore: Authorization header is ignored in WebSocket request

Describe the bug

The Authorization header is removed in WebSocket request.

To Reproduce

I try to set Authorization header in .NET 5 console app for WebSocket connection:

var client = new ClientWebSocket();
client.Options.SetRequestHeader("Authorization", "token");
client.Options.SetRequestHeader("CustomAuthorization", "custom-token");
await client.ConnectAsync(new Uri(_url, CancellationToken.None);

On the other side, there is ASP.NET WebAPI with the code in a middleware:

public async Task Invoke(HttpContext context)
{
	if (!context.WebSockets.IsWebSocketRequest)
	{
		await context.Response.WriteAsync("Only WebSocket requests are allowed at this endpoint.");
		await context.Response.CompleteAsync();
		return;
	}

	Console.WriteLine($"Authorization = {context.Request.Headers["Authorization"]}");
	Console.WriteLine($"CustomAuthorization = {context.Request.Headers["CustomAuthorization"]}");	
	...
}

result:

Authorization = CustomAuthorization = custom-token

Can anyone explain why the Authorization header was removed? Is it by design? If yes, then where I can find docs for that? Are there other headers that will be removed? Please suggest

Perhaps the issue should be created in dotnet/runtime. Please correct me if I am wrong

Further technical details

  • ASP.NET Core 5.0.301

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 16 (16 by maintainers)

Most upvoted comments

Ok, now I remember, for security reasons we don’t preserve the authentication header on redirects. This is by design behavior.

https://github.com/dotnet/runtime/blob/3db6ec5ab895e57073dc657f1462f86d8e0d3d79/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs#L53-L54

Lets keep this open and see if that behavior makes sense