Course contentsShow
← C#
Lesson 1456 of 1,90813. Real-time Communication with SignalRFree lesson

Authorization Policy Enforcement

Apply granular role-based access control to individual Hub methods and group subscriptions.

In this lesson, you will learn how to enforce granular security policies on SignalR Hubs to ensure that only authorized users can invoke specific methods or join restricted communication groups.

Securing Hub Methods

SignalR relies on the standard [Authorize] attribute to enforce security. However, since Hub methods are essentially RPC calls, you can apply these attributes at the class level for global protection, or at the method level for fine-grained control.

If you have a ChatHub where only "Admins" should be allowed to broadcast system-wide alerts, you apply the policy directly to that specific method:

[Authorize]
public class ChatHub : Hub
{
    public async Task SendMessage(string message) 
    {
        await Clients.All.SendAsync("Receive", message);
    }

    [Authorize(Policy = "AdminOnly")]
    public async Task SendSystemAlert(string alert)
    {
        await Clients.All.SendAsync("SystemAlert", alert);
    }
}

Controlling Group Subscriptions

Authorization becomes more complex when managing groups. Simply because a user can access the Hub doesn't mean they should be allowed to join a sensitive group. To enforce this, perform an authorization check inside the method before invoking Groups.AddToGroupAsync.

public async Task JoinPrivateChannel(string channelId)
{
    // Custom check: Does the current user have permission to this channel?
    var canAccess = await _channelService.UserHasAccess(Context.UserIdentifier, channelId);
    
    if (canAccess)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, channelId);
    }
    else
    {
        throw new HubException("You are not authorized to join this group.");
    }
}

By leveraging Context.UserIdentifier (which maps to the ClaimTypes.NameIdentifier), you ensure that group subscriptions remain tied to the verified identity of the user. Always validate the business logic inside the Hub method to prevent unauthorized users from "guessing" group names to gain access to sensitive streams.

Key Takeaway: Use the [Authorize] attribute for declarative method-level protection and manual policy validation within Hub methods to gate access to dynamic groups.