0
votes

I have two requirements:

  1. I want my SignalR hubs to require authentication
  2. When the request comes in, I want it to come with a JWT token so that I can get user data.

It's important to note that I'm using SignalR Core which is still in Alpha and looks like there's been some changes in the API.

I've been doing some research on this for the past couple of hours and I'm a bit confused about how to both pass the JWT Token on the client side and receive it on the server side.

1
Have you looked at samples - github.com/aspnet/SignalR/tree/dev/samples? There is a server and C# and TS/JS client sample showing how to handle JWT auth.Pawel

1 Answers

0
votes

You can pass the jwt as a querystring parameter when you connect to the hub and then add the token as a header in your middleware. Heres a very basic example.

JS

let connection = new signalR.HubConnection('http://localhost/messagesHub', {jwtBearer: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ'});

connection.on('Send', data => {
    console.log(data);
});

connection.start()
          .then(() => connection.invoke('Send', 'test'));

Add to your Startup.cs Configure{} near the top, as high as possible

app.Use(async (context, next) =>
{
    if (context.Request.Query.TryGetValue("token", out var token))
    {
        context.Request.Headers.Add("Authorization", $"Bearer {token}");
    }
    await next.Invoke();
});

Since the token is added in the header in your middleware, it should work as normal JWT auth with the same config as you would use in any other app.

Be aware you are passing a JWT in the querystring though so just be aware of the different security issues and make changes to help combat them (like https)