Add To Context Items in SignalR Middleware

Viewed 819

So I want to setup a User Middleware which works for SignalR Hubs and Controllers. It works fine with normal requests but with signalr it gets called but doesnt add to context. Is it even possible? If so how can i do it?

namespace PortalCore.Middleware
{
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;

        public JwtMiddleware(RequestDelegate next)
        {
            _next = next;

        }

        public async Task Invoke(HttpContext context, AuthService authService)
        {
            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
            if (token != null)
            {
                AttachUserToContext(context, authService, token);
            }
       

            await _next(context);
        }

        private async void AttachUserToContext(HttpContext context, AuthService authService, string token)
        {
            User user = null;
            var tokenHandler = new JwtSecurityTokenHandler();
            try
            {
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey =
                        new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(authService.SecretKey)),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);
                var jwtToken = (JwtSecurityToken)validatedToken;
                user = await authService.GetUserByUid(jwtToken.Claims.FirstOrDefault()?.Value);
            }
            catch (Exception e)
            {

            } 
            context.Items["User"] = user;
        }
    }
}

1 Answers

if you want to check auth of signalR hub then you can do it with query string.you can send token with signalR client url.After take token from query string and set to context.

Hub Code:

 [Authorize]
 public class ChatHub : Hub
    

you can add token in Context :

OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrWhiteSpace(accessToken) &&
                            (path.StartsWithSegments("/api/hubs/chatHub")))
                        {
                            context.Token = accessToken;
                        }

                        return Task.CompletedTask;
                    },
Related