Search code examples
model-view-controllersignalrsignalr-hubsignalr.client

Role Based Notification, Along with Groups using Signalr in MVC 5


i am a beginner in signalR and Need to make an application where there are many users having many roles, and there should be three channels of sending notification to clients 1. Public (Used For All) 2. Private (Sending Notification to Single Person) 3. Group and Sub Group (Sending Notification to the persons who are member of some group or sub-group)

Problem is i am unable to understand the user differentiation in SignalR and not getting the concept of groups.

Anyone please Guide me


Solution

  • First of all, you can start to read the Microsoft documentation about the groups. Then you can read the authorization documentation so you would be able to create groups and manage users for each role.

    What you can do is, when the client connects to the Hub, and assuming you know the users role (using the context and the authorization) you will add them to those 3 groups.

    Then it is easy to send message to those groups, you have such examples everywhere in the stackOverflow and the internet.

    Hope this helps you.

    Code example:

    /// <summary>
    /// Called when a new connection is established with the hub.
    /// </summary>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public override async Task OnConnectedAsync()
    {
        // 1. Add the use to the public group
    
        await this.Groups.AddToGroupAsync( this.Context.ConnectionId, "PublicGroup");
    
        // 2. Add user to the private channel, single person
    
        await this.Groups.AddToGroupAsync(this.Context.ConnectionId, this.Context.User.Identity.Name);
    
        if (this.Context.User.IsInRole("Admin"))
        {
            // 3. Add the user to the Admin group
    
            await this.Groups.AddToGroupAsync(this.Context.ConnectionId, "Admin");   
        }
    
        // add to other groups...
    
        await base.OnConnectedAsync();
    }