Retrieve bearer jwt token from SignalR request

Viewed 57

I need to retrieve jwt token from SignalR request. I need this not for autheticate (this works fine), but for further tasks on token. Ideally will be if I can retrieve it on Hub level.

My Hub class

    [Authorize(AuthenticationSchemes = "Bearer")]
    public class MyHub : Hub
    {
        private readonly IMyService _myService;

        public myHub(IMyService myService)
        {
            _myService = myService;
        }

        public async Task GetSomething()
        {
            await Clients.Caller.SendAsync("GetSomething", await _myService.GetSome();
        }
    }
1 Answers

This should work, you can do it in a hub method :

    var httpContext = Context.GetHttpContext();
    if (httpContext.Request.Headers.TryGetValue("Authorization", out var authorizationValues))
        {
            var tokenWithBearer = authorizationValues.FirstOrDefault(s => s.Contains("Bearer", StringComparison.InvariantCultureIgnoreCase));
            if (tokenWithBearer != null)
            {
                // now trunc it at left to remove "Bearer " and get your token
            }
        }

Done using extension method GetHttpContext() in Microsoft.AspNetCore.SignalR, hoping that you will also be in Core.

Related