skip to content

In ASP.NET Core SignalR, how does Clients.User decide which connections belong to a user, and how do you change that with IUserIdProvider?

level: middleimportance: should knowfreq 50%

answer

  1. Context.UserIdentifier
  2. DefaultUserIdProvider reads ClaimTypes.NameIdentifier
  3. fixed once, at the handshake
  4. every tab and device receives it
  5. AddSingleton<IUserIdProvider, ...>()

basics

~20 s

Clients.User(id) reaches every connection whose Context.UserIdentifier equals id. The identifier is computed once per connection by IUserIdProvider; the default reads the ClaimTypes.NameIdentifier claim. Register your own IUserIdProvider as a singleton to use, say, an email claim.

solid answer

~40 s

When a connection completes its handshake, SignalR calls `IUserIdProvider.GetUserId(HubConnectionContext)` and stores the result as the connection's `UserIdentifier`, exposed in hubs as `Context.UserIdentifier`. The default `DefaultUserIdProvider` returns the value of the `ClaimTypes.NameIdentifier` claim, or `null` for an anonymous connection. `Clients.User("42")` then reaches every connection with that identifier, so a member's laptop, phone and second tab all get the message, and `Clients.Users(ids)` takes several. The comparison is case-sensitive. To key users differently, for example by an email claim, implement `IUserIdProvider` and register it with `builder.Services.AddSingleton<IUserIdProvider, EmailUserIdProvider>()`, since `AddSignalR` only adds the default with `TryAddSingleton`. The identifier is fixed for the connection's lifetime; the user must be authenticated when connecting for it to be set.

code

csharp · 17 lines
csharp
public class BookingNotifier(IHubContext<SpaceHub> hub)
{
    // Reaches the member on every device and tab they have connected.
    public Task RoomMovedAsync(string memberId, int newRoomId) =>
        hub.Clients.User(memberId).SendAsync("BookingMoved", newRoomId);
}

public class SpaceHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        // Null for anonymous connections: no NameIdentifier claim.
        if (Context.UserIdentifier is null)
            await Groups.AddToGroupAsync(Context.ConnectionId, "guests");
        await base.OnConnectedAsync();
    }
}

go deeper

for a junior

Know that Clients.User sends to a person on all their connections and that Context.UserIdentifier holds the id.

for a middle

Explain DefaultUserIdProvider's NameIdentifier claim, the handshake-time computation, case sensitivity and how to register a custom IUserIdProvider.

for a senior

Handle the edges: null ids for anonymous users, ids fixed per connection, many connections per user and reach across servers.

for a principal

Pick one user key shared by identity, bookings and SignalR, so notifications never depend on a second mapping that can drift.

## Users versus connections A SignalR **connection** is one client instance: one browser tab, one phone app. A **user** is a person, who may hold several connections at once. SignalR lets you address the person with `Clients.User(userId)` instead of tracking each connection id yourself. In the co-working space app, "your meeting room booking was moved" goes to the member, on every device they have open. ## Where the user id comes from 1. The client connects; authentication middleware has already set the connection's `ClaimsPrincipal` if the request was authenticated. 2. During the hub handshake, SignalR calls **`IUserIdProvider.GetUserId(HubConnectionContext connection)`** once. 3. The returned string is stored as the connection's **`UserIdentifier`**, visible in hubs as `Context.UserIdentifier`. The default, **`DefaultUserIdProvider`**, returns `connection.User.FindFirst(ClaimTypes.NameIdentifier)?.Value`. For an anonymous connection there is no such claim, so the identifier is `null` and `Clients.User` can never reach that connection. ## Sending to users | Target | Reaches | |---|---| | `Clients.User(id)` | every connection whose `UserIdentifier` equals `id` | | `Clients.Users(ids)` | every connection of any listed user | | `Clients.Client(connectionId)` | exactly one connection | The default lifetime manager compares identifiers with an **ordinal, case-sensitive** comparison, and the docs repeat that the user identifier is case-sensitive. If ids come from emails, normalise their casing in the provider. The same targets exist on an injected hub context, which is how a booking service outside the hub notifies a member. ## Customising the identifier When the name identifier claim is not what the rest of the system uses, for example when bookings are keyed by email, implement the interface: ```csharp public sealed class EmailUserIdProvider : IUserIdProvider { public string? GetUserId(HubConnectionContext connection) => connection.User.FindFirst(ClaimTypes.Email)?.Value?.ToLowerInvariant(); } builder.Services.AddSingleton<IUserIdProvider, EmailUserIdProvider>(); builder.Services.AddSignalR(); ``` Registration notes: - `AddSignalR` registers the default with **`TryAddSingleton`**, so your registration wins whether it comes before `AddSignalR` (the default is then skipped) or after it (the last registration is resolved). - Register it as a **singleton**; the provider is resolved by singleton SignalR infrastructure. - Keep it cheap and synchronous: it runs on every connection's handshake. ## Edge cases interviewers probe - **The id is fixed for the connection.** Changing a claim later, or the user signing out in another tab, does not change `UserIdentifier` on an open connection; it takes a new connection. - **Anonymous users** have a `null` identifier. Give guests their own group, or require authentication on the hub. - **Many connections per user.** A presence feature has to count them; one disconnect does not mean the person left. - **Multiple servers.** `Clients.User` reaches connections on other servers only with a backplane or the Azure SignalR Service. - **User ids are not secrets.** Sending to a user only routes messages; it does not check that the sender may message that user.

  • A member opens the app on a laptop and a phone. How many messages does Clients.User(memberId) send, and why?
    Two, one per connection. `Clients.User` selects every connection whose `UserIdentifier` matches, and each device and tab has its own connection with the same identifier. That is the point of user targeting, and also why a presence feature must count connections per user.
  • Why does Clients.User("[email protected]") miss a member whose id was stored as [email protected]?
    User identifiers are compared case-sensitively, with an ordinal comparison in the default lifetime manager. A provider that builds ids from emails should normalise them, for example to lower case, and every sender must use the same normalised form.

  • Clients.User reaches only the most recent connection of that user.
  • The default user id is the ClaimTypes.Name claim, the user's display name.
  • User ids are compared case-insensitively.
  • Anonymous connections get a generated user id that Clients.User can target.
  • Changing a claim updates Context.UserIdentifier on the open connection.