Royi Namir
Royi Namir

Reputation: 148744

Multiple Hubs on Signal/R - instantiating from client side?

Let's say I have 2 hubs.

One for admin operations and one for users operations :

[Authorize(Roles = "Admin")]
public class MyHubAdmin : Hub
{..}

&

[Authorize(Roles = "Users")]
public class MyHubUsers : Hub
{..}

Currently my client supports only admin :

var _myHub = $.connection.myHubAdmin;

And I know I that now , I have another one which should be treated :

var _myHub = $.connection.myHubUsers ;

p.s. ( I know they share the same connecion)

But a client is a client

He did login 2 minutes ago , So I know who he is (admin vs user)

So how does my JS client should look like :

Should it be something like this ?

var _myHub=null;

if (check if user)  //or admin...
{
    _myHub = $.connection.myHubUsers;
}
else 
{
    _myHub = $.connection.myHubAdmin;
}

Question

Regarding the "check if user" function :

It seems that I can do it in 2 ways :

Is this the right way of doing it ?

( in short : how to instantiate a hub according to a user identity - on the client side)

Upvotes: 1

Views: 726

Answers (1)

N. Taylor Mullen
N. Taylor Mullen

Reputation: 18311

When building in multi-layer security into your SignalR application try to keep in mind that you may eventually want to have more than just 2 levels (regular user & admin). By keeping this in mind you can make your code cleaner and more useable for the future.

That being said, only segregate functions to a different hub if they truly make sense to be segregated. Lets take a chat example where we have 2 types of users, regular users and admin users.

Regular users:
- Chat

Admin users can do everything regular users can do including the following:
- Mute users
- Remotely restart server

With that in mind I'd argue that Muting users and Chatting could belong on a ChatHub where remotely restarting a server should probably belong on an AdminHub.

So the question then is how can we handle this on the client?

A clean approach could be to include a separate script on the page based on the security level.

You can have a default Chat.js script that will be the API for referencing the ChatHub that is always included. Now if your user happens to be an admin you can include an Admin.js file in your page that will add the admin capability and the admin API for referrencing the AdminHub. Lastly you'll have a final script that starts the SignalR connection and takes care of all of the grunt work.

With the JS infrastructure in place and an Authorize attribute on the MuteUser function within the ChatHub and another Authorize attribute on the AdminHub class; your users and admins can now coexist gracefully.

Of course prior to all this you've needed to Authenticate the user to determine their identity.

Hope this helps!

Upvotes: 2

Related Questions