2

I am authenticating the user using JWT Tokens. Its working correctly, the Context.User is populated correctly. The problem is its just one user, does the hub not have a user per connection?

In the OnNotification method I want to cycle through all the current connections, verify if the user has permissions to see what I am about to send, then send if he/she has and not otherwise.

How can I acehieve this?

  [Authorize]
  public class NotifyHub : Hub {
    private readonly MyApi _api;

    public NotifyHub(MyApi api) {
      _api = api;
      _api.Notification += OnNotification;
    }

    private async void OnNotification(object sender, Notification notification) {
      //  can access Context.User here
      await Clients.All.SendAsync("Notification", notification);
    }
  }
Colton Scottie
  • 807
  • 1
  • 8
  • 22
  • 1
    An example of a work-around [Here](https://stackoverflow.com/a/13514344/2174170). But you'll use `Context.User` instead. – Dumisani Jul 22 '19 at 14:16

1 Answers1

0

When you are using a Hub you can Invoke methods on the caller client (Clients.Caller), one specific client (Clients.User("client_id")), a group of clients (Clients.Group("group name")), and all the clients (Clients.All).

If none of those fit your needs you should implement your own class that tracks the users that are connected to the Hub (pretty easy because the Hub has OnConnectedAsync and OnDisconnectedAsync event handlers for that, I usually do it with a singleton class and a List, and some locks, just for thread safety).

Note that Hubs are transient. They don't exist until they get a request from a client, and immediately disposed after the request finished. So it's not advised to subscribe for events. Hubs are IDisposable, so the framework will dispose them after a request finished, so by the time the event arrives they might have been disposed. You should rather inject an IHubContext<NotifyHub> (that's what stores the clients of the hub in the memory) into your MyApi and use it there with your connected user storing class.

Koppa Péter
  • 264
  • 1
  • 8
  • My hub is added as a singleton `services.AddSingleton();` – Colton Scottie Jul 22 '19 at 14:39
  • I don't really think that's a great idea, at least I haven't seen anybody doing that :D. For example by making your hub singleton your can't access any scoped services within, and I suppose the resources used by the hub won't be freed either if it's a singleton. Also thread safety can also be a problem if your hub is a singleton. – Koppa Péter Jul 22 '19 at 15:00
  • But wouldn't it be a performance problem if my hub is created 100 times a second for outgoing job progress updates? – Colton Scottie Jul 22 '19 at 15:42
  • I don't think it would have been designed that way if it had great impact on the performance. – Koppa Péter Jul 22 '19 at 17:27