LESSON 5 OF 14

5. User-Based and Group-Based Messaging

Build secure private messaging and project-room communication with SignalR user, connection, and group targets.

45 dk 48

Introduction

In the previous lessons, we created a Hub, connected a JavaScript client, and used shared message contracts for type-safe communication. This lesson focuses on choosing the destination of a message more precisely. Instead of broadcasting to every connected client, we will send messages to a specific user, a single connection, or all connections that belong to the same task or project group.

These patterns are common in real applications. A user notification should usually reach all browser sessions belonging to that account. A response intended only for the current browser tab should target one connection. A project update should be delivered to every participant in the relevant project room. The examples assume an ASP.NET Core application using JWT authentication and a TypeScript-based SignalR client.

Users, connections, and groups in SignalR

User targets

A user may connect from a desktop browser, a mobile device, or several browser tabs at the same time. Each connection has a different ConnectionId, but multiple connections can be associated with the same SignalR user identifier. When you use Clients.User(userId), all active connections associated with that user receive the message.

By default, SignalR uses the NameIdentifier claim as the user identifier. When issuing JWTs, make sure that this claim contains a stable and unique identifier. An email address can be used, but a permanent account ID is usually safer when email addresses can change.

Connection targets

Clients.Client(connectionId) sends a message only to the specified connection. This is useful for returning the result of an operation to the browser tab that initiated it or for sending a tab-specific state update. Connection IDs are temporary. They can change after reconnection and must not be treated as trusted authorization data.

Group targets

A group is a collection of connections associated with an application-defined name. A connection can belong to multiple groups. With Clients.Group(groupName), the server sends a message to all connections in that group. Projects, tasks, teams, support conversations, and game lobbies are all good candidates for group modeling.

SignalR groups are not permanent database records. Group membership is lost when a connection is closed. A client that reconnects may need to join its groups again. For this reason, permanent project membership and temporary SignalR group membership should be treated as separate concepts.

Creating message targets on the server

The following example uses a Hub for project messaging. The message contract is intentionally small and can be aligned with the shared contract introduced in the previous lesson.

public sealed record ProjectMessage(
    string ProjectId,
    string SenderId,
    string Text,
    DateTimeOffset SentAt);

public interface IProjectMembershipService
{
    Task<bool> IsMemberAsync(string userId, string projectId,
        CancellationToken cancellationToken = default);
}

The membership service determines whether a user actually has access to a project. We should never trust a group name supplied by the client as proof of authorization. A client can send any string it wants; the server must make the access decision.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

[Authorize]
public sealed class ProjectHub : Hub
{
    private readonly IProjectMembershipService _membership;

    public ProjectHub(IProjectMembershipService membership)
    {
        _membership = membership;
    }

    public async Task JoinProject(string projectId)
    {
        var userId = Context.UserIdentifier;
        if (string.IsNullOrWhiteSpace(userId))
            throw new HubException("The user identifier is missing.");

        var isMember = await _membership.IsMemberAsync(
            userId, projectId, Context.ConnectionAborted);

        if (!isMember)
            throw new HubException("You do not have access to this project.");

        var groupName = ProjectGroup(projectId);
        await Groups.AddToGroupAsync(
            Context.ConnectionId, groupName, Context.ConnectionAborted);

        await Clients.Caller.SendAsync(
            "ProjectJoined", projectId, Context.ConnectionAborted);
    }

    public async Task LeaveProject(string projectId)
    {
        var groupName = ProjectGroup(projectId);
        await Groups.RemoveFromGroupAsync(
            Context.ConnectionId, groupName, Context.ConnectionAborted);

        await Clients.Caller.SendAsync(
            "ProjectLeft", projectId, Context.ConnectionAborted);
    }

    public async Task SendProjectMessage(string projectId, string text)
    {
        var userId = Context.UserIdentifier;
        if (string.IsNullOrWhiteSpace(userId))
            throw new HubException("The user identifier is missing.");

        if (string.IsNullOrWhiteSpace(text) || text.Length > 2_000)
            throw new HubException("The message length is invalid.");

        var isMember = await _membership.IsMemberAsync(
            userId, projectId, Context.ConnectionAborted);

        if (!isMember)
            throw new HubException("You cannot send messages to this project.");

        var message = new ProjectMessage(
            projectId,
            userId,
            text.Trim(),
            DateTimeOffset.UtcNow);

        await Clients.Group(ProjectGroup(projectId))
            .SendAsync("ProjectMessageReceived", message,
                Context.ConnectionAborted);
    }

    public Task SendToThisConnection(string text)
    {
        return Clients.Client(Context.ConnectionId)
            .SendAsync("PrivateConnectionMessage", text,
                Context.ConnectionAborted);
    }

    public Task SendToUser(string userId, string text)
    {
        return Clients.User(userId)
            .SendAsync("UserMessageReceived", text,
                Context.ConnectionAborted);
    }

    private static string ProjectGroup(string projectId)
        => $"project:{projectId}";
}

Clients.Caller targets the connection that invoked the method, Clients.Client targets a specific connection, Clients.User targets every active connection for a user, and Clients.Group targets group members. A method that allows arbitrary clients to send messages to arbitrary users is usually unsafe. In production, replace that pattern with an authorized workflow or a server-side application service.

Mapping JWT identity to a SignalR user

In a JWT-based application, the Hub endpoint must be mapped after authentication and authorization middleware are configured. The user ID in the token should become Context.UserIdentifier.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Jwt:Authority"];
        options.Audience = builder.Configuration["Jwt:Audience"];
    });

builder.Services.AddAuthorization();
builder.Services.AddSignalR();
builder.Services.AddScoped<IProjectMembershipService,
    ProjectMembershipService>();

var app = builder.Build();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapHub<ProjectHub>("/hubs/projects");
app.Run();

If the default claim mapping does not match the way your tokens are issued, define a custom IUserIdProvider. The following provider uses the sub claim as the user ID.

using System.Security.Claims;
using Microsoft.AspNetCore.SignalR;

public sealed class SubjectUserIdProvider : IUserIdProvider
{
    public string? GetUserId(HubConnectionContext connection)
        => connection.User?.FindFirstValue("sub");
}

// Program.cs
builder.Services.AddSingleton<IUserIdProvider,
    SubjectUserIdProvider>();

The selected value must be unique across all users. If a non-unique claim is used, a message intended for one account can reach another account. Also remember that the identity is established when the connection starts. For sensitive operations, membership or role changes should be checked against current application data rather than relying only on a cached principal.

TypeScript client

Install the client package in the frontend project:

npm install @microsoft/signalr

A token factory can provide the JWT when the connection starts or reconnects. In a real application, keep tokens in an appropriate secure storage strategy and never write them to URLs or logs.

import {
  HubConnection,
  HubConnectionBuilder,
  LogLevel
} from "@microsoft/signalr";

const accessToken = "JWT_TOKEN_FROM_AUTH_FLOW";

const connection: HubConnection = new HubConnectionBuilder()
  .withUrl("/hubs/projects", {
    accessTokenFactory: () => accessToken
  })
  .withAutomaticReconnect()
  .configureLogging(LogLevel.Information)
  .build();

connection.on("ProjectJoined", (projectId: string) => {
  console.log(`Joined project: ${projectId}`);
});

connection.on("ProjectMessageReceived", (message: ProjectMessage) => {
  renderProjectMessage(message);
});

connection.on("UserMessageReceived", (text: string) => {
  showNotification(text);
});

connection.on("PrivateConnectionMessage", (text: string) => {
  showLocalResult(text);
});

await connection.start();
await connection.invoke("JoinProject", "project-42");

await connection.invoke(
  "SendProjectMessage",
  "project-42",
  "The new report has been uploaded."
);

type ProjectMessage = {
  projectId: string;
  senderId: string;
  text: string;
  sentAt: string;
};

Server method names and parameter order must match the client invocation exactly. Do not insert user-provided message text directly into HTML. Render it as text or use a suitable output-encoding layer. SignalR transports the message; XSS protection remains the responsibility of the application.

Managing groups safely

Use a predictable naming convention instead of accepting arbitrary group names from the client. A prefix such as project:{id} reduces collisions between groups used for different features. The JoinProject method must fail when the user is not a member of the requested project.

Joining and leaving should be designed to be idempotent. Joining the same group twice does not need to produce an application error. Similarly, leaving a group that the connection is not currently in can safely complete.

If a user opens two tabs and joins the same project, both tabs are separate connections and both are added to the group. When one tab leaves, the other tab remains a member. If the user is permanently removed from a project, blocking only future joins is not enough. Later message operations should also validate current membership on the server.

Testing with separate browser sessions

  1. Run the application and obtain JWT tokens for two different users.
  2. Open User A in a regular browser window and User B in a private window.
  3. Open a third tab using a second connection for User A.
  4. Send a user-targeted notification and verify that both User A connections receive it.
  5. Join User A and User B to the same project and verify that all three connections receive a group message.
  6. Remove User B from the project or delete the membership record, then verify that a new message attempt is rejected.
  7. Invoke SendToThisConnection from one User A tab and verify that the other tab does not receive the message.

Common mistakes

  • Treating the group name as authorization: A client sending the correct group name does not prove that it has access.
  • Choosing a non-unique user ID: If email or username values are not unique, notifications can be routed to the wrong account.
  • Treating a connection ID as permanent: Reconnection can produce a new ID; use users or groups for durable targeting.
  • Using group membership as a database: A SignalR group represents current connection membership, not permanent project membership.
  • Trusting client input: Validate the project ID, message length, and current authorization on the server.
  • Forgetting client handlers: Without a matching connection.on handler, the UI will not react to a server message.

Short practice exercise

Create task:{taskId} groups for a task board. Allow JoinTask only when the user has access to the task. Make UpdateTaskStatus broadcast status changes only to the relevant task group. Also send a private notification through Clients.User to the user assigned to the task.

Test the feature with two tabs for the same user and two windows for different users. Prepare a small test table proving that group messages reach only task-group members, while the assigned-user notification reaches all active connections for that user.

Conclusion

This lesson introduced three SignalR targeting levels: one connection, one user, and one group. A user target reaches all active sessions for an account, a connection target responds to one browser session, and a group target broadcasts to project or task participants.

A secure design uses predictable group names, validates membership on the server, derives user IDs from a unique claim, and keeps permanent business rules separate from SignalR’s temporary group state. In the next lessons, we will extend this model with live notifications, real-time data updates, and richer client-side state management.

Sources