BotSharp/src/Plugins/BotSharp.Plugin.ChatHub/WebSocketsMiddleware.cs

32 lines
1 KiB
C#
Raw Normal View History

2023-11-28 03:19:07 +00:00
using Microsoft.AspNetCore.Http;
2024-05-06 07:37:58 +00:00
using System.Text.RegularExpressions;
2023-11-28 03:19:07 +00:00
namespace BotSharp.Plugin.ChatHub;
public class WebSocketsMiddleware
{
private readonly RequestDelegate _next;
public WebSocketsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
2024-05-06 07:37:58 +00:00
var request = httpContext.Request;;
2024-05-06 22:31:52 +00:00
var messageFileRegex = new Regex(@"/conversation/[a-z0-9-]+/message/[a-z0-9-]+/file/[a-z0-9-]+", RegexOptions.IgnoreCase);
2023-11-28 03:19:07 +00:00
// web sockets cannot pass headers so we must take the access token from query param and
// add it to the header before authentication middleware runs
2024-05-06 22:31:52 +00:00
if ((request.Path.StartsWithSegments("/chatHub", StringComparison.OrdinalIgnoreCase)
|| messageFileRegex.IsMatch(request.Path.Value ?? string.Empty)) &&
2023-11-28 03:19:07 +00:00
request.Query.TryGetValue("access_token", out var accessToken))
{
2024-02-14 23:45:28 +00:00
request.Headers["Authorization"] = $"Bearer {accessToken}";
2023-11-28 03:19:07 +00:00
}
await _next(httpContext);
}
}