English
From services to browsers
Step 1. The notifier
Why. In topic 10 the business layer declared IChatNotifier and called it after every commit; until now the NullChatNotifier swallowed the events. The web layer implements the interface with SignalR: each event goes to the group of its chat (Fig. 14.3).
Fig. 14.3. One message, end to end
Alice receives her own message twice — as the HTTP response and as the event, in either order. The Angular store merges messages by id (topic 19), so this is harmless and keeps the server simple: there is no "everyone except the sender" logic that would break when Alice has a second tab open.
Do.
cs
using Chatex.Core.Abstractions;
using Chatex.Core.Messages;
using Microsoft.AspNetCore.SignalR;
namespace Chatex.Api.Hubs;
/// <summary>Pushes the business layer's chat events to the chat's SignalR group.</summary>
internal sealed class SignalRChatNotifier(IHubContext<ChatHub, IChatClient> hub, PresenceTracker tracker) : IChatNotifier
{
public Task MessageCreatedAsync(MessageDto message, CancellationToken cancellationToken = default) =>
Chat(message.ChatId).MessageCreated(message);
public Task MessageUpdatedAsync(MessageDto message, CancellationToken cancellationToken = default) =>
Chat(message.ChatId).MessageUpdated(message);
public Task MessageDeletedAsync(Guid chatId, Guid messageId, CancellationToken cancellationToken = default) =>
Chat(chatId).MessageDeleted(chatId, messageId);
public Task MessagesReadAsync(Guid chatId, Guid userId, Guid lastReadMessageId, CancellationToken cancellationToken = default) =>
Chat(chatId).MessagesRead(chatId, userId, lastReadMessageId);
public async Task MembersAddedAsync(Guid chatId, IReadOnlyCollection<Guid> userIds, CancellationToken cancellationToken = default)
{
// Join the new members' open connections first, so they get this event and everything after it without reconnecting.
var group = ChatHub.GroupName(chatId);
foreach (var userId in userIds)
{
foreach (var connectionId in tracker.GetConnections(userId))
{
await hub.Groups.AddToGroupAsync(connectionId, group, cancellationToken);
}
}
await hub.Clients.Group(group).MembersAdded(chatId, [.. userIds]);
}
public async Task MemberRemovedAsync(Guid chatId, Guid userId, CancellationToken cancellationToken = default)
{
// Send first, so the removed user learns about it too, then stop their events from this chat.
var group = ChatHub.GroupName(chatId);
await hub.Clients.Group(group).MemberRemoved(chatId, userId);
foreach (var connectionId in tracker.GetConnections(userId))
{
await hub.Groups.RemoveFromGroupAsync(connectionId, group, cancellationToken);
}
}
public Task ChatUpdatedAsync(Guid chatId, CancellationToken cancellationToken = default) =>
Chat(chatId).ChatUpdated(chatId);
public Task ChatDeletedAsync(Guid chatId, CancellationToken cancellationToken = default) =>
Chat(chatId).ChatDeleted(chatId);
private IChatClient Chat(Guid chatId) => hub.Clients.Group(ChatHub.GroupName(chatId));
}IHubContext<ChatHub, IChatClient>sends from outside a hub;hub.Clients.Group(name)returns anIChatClient, so the events are typed calls such as.MessageCreated(message).- Membership changes touch the groups. A new member's open connections are added to the group before
MembersAddedis sent, so the new member receives this event and every later one without reconnecting. A removed member getsMemberRemovedfirst — so the client learns about it — and is then taken out of the group. - The notifier is a singleton: the hub context and the tracker are singletons too.
Step 2. Tokens for WebSocket connections
Why. A browser cannot set an Authorization header on a WebSocket or Server-Sent Events request. The SignalR JavaScript client therefore sends the access token in the query string: /hubs/chat?access_token=…. The JWT handler must take it from there — but only for hub paths: tokens in URLs end up in server logs and browser histories, so no other endpoint should accept them.
Step 3. Register SignalR
Do. Complete AddApi (new lines in green). The method and its comment are now final:
cs
using System.Text.Json;
using System.Text.Json.Serialization;
using Chatex.Api.Hubs;
using Chatex.Api.Infrastructure;
using Chatex.Api.Maintenance;
using Chatex.Core.Abstractions;
using Chatex.Core.Auth;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace Chatex.Api;
public static class DependencyInjection
{
/// <summary>The request body limit for everything except file uploads.</summary>
public const long MaxRequestBodyBytes = 1024 * 1024;
/// <summary>
/// Registers what the HTTP layer needs on top of <c>AddCore</c>: JSON, JWT auth, ProblemDetails, OpenAPI and
/// the SignalR hub. Call it before <c>AddCore</c> so the SignalR <see cref="IChatNotifier"/> wins.
/// Reads the optional <c>Presence</c>, <c>RateLimiting</c> and <c>Maintenance</c> sections and
/// <c>DataProtection:KeysPath</c>.
/// </summary>
public static IServiceCollection AddApi(this IServiceCollection services, IConfiguration configuration)
{
// Without a key folder the keys live in memory and change on every restart. Nothing persistent depends on
// them yet, but Identity tokens (password reset, email confirmation) will.
var dataProtection = services.AddDataProtection().SetApplicationName("Chatex");
if (configuration["DataProtection:KeysPath"] is { Length: > 0 } keysPath)
{
dataProtection.PersistKeysToFileSystem(new DirectoryInfo(keysPath));
}
services.AddOptions<MaintenanceOptions>()
.BindConfiguration(MaintenanceOptions.Section)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddHostedService<MaintenanceService>();
// JSON bodies are small; the upload endpoints raise this per request (FileUploadExtensions.AcceptsFileUpTo).
services.Configure<KestrelServerOptions>(o => o.Limits.MaxRequestBodySize = MaxRequestBodyBytes);
services.ConfigureHttpJsonOptions(o =>
o.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)));
services.AddSignalR().AddJsonProtocol(o =>
o.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)));
services.AddOptions<PresenceOptions>()
.BindConfiguration(PresenceOptions.Section)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddSingleton<PresenceTracker>();
services.AddSingleton<PresenceService>();
services.AddSingleton<IUserIdProvider, SubClaimUserIdProvider>();
services.AddSingleton<IChatNotifier, SignalRChatNotifier>();
services.AddProblemDetails();
services.AddChatexRateLimiting();
// Malformed bodies answer 400 (turned into problem details by UseStatusCodePages) in every environment,
// instead of throwing to the exception handler in Development.
services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = false);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<JwtOptions>>((bearer, jwtOptions) =>
{
var jwt = jwtOptions.Value;
bearer.MapInboundClaims = false;
bearer.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwt.Issuer,
ValidAudience = jwt.Audience,
IssuerSigningKey = jwt.CreateSigningKey(),
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
NameClaimType = JwtRegisteredClaimNames.UniqueName,
ClockSkew = TimeSpan.FromSeconds(30),
};
// Browsers cannot send headers on WebSocket and SSE requests, so the SignalR client puts the token
// in the query string. Accept it there only for hub paths, to keep tokens out of other URLs and logs.
bearer.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var token = context.Request.Query["access_token"].ToString();
if (token.Length > 0 && context.HttpContext.Request.Path.StartsWithSegments("/hubs"))
{
context.Token = token;
}
return Task.CompletedTask;
},
};
});
services.AddAuthorization();
services.Configure<ForwardedHeadersOptions>(o =>
o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto);
services.AddOpenApi(o =>
{
o.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
o.AddOperationTransformer<BearerSecuritySchemeTransformer>();
});
return services;
}
}AddSignalR().AddJsonProtocol(...)with the same camelCase enum converter as HTTP, so aChatDtolooks the same in a response and in an event.PresenceOptions(the grace period), the tracker and the presence service as singletons;SubClaimUserIdProviderreplaces SignalR's defaultIUserIdProvider.AddSingleton<IChatNotifier, SignalRChatNotifier>()— this is whyAddApimust run beforeAddCore:AddCoreregisters theNullChatNotifierwithTryAddSingleton, which now finds a notifier and does nothing (topic 10).bearer.Events.OnMessageReceivedtakes the token fromaccess_tokenwhen the path starts with/hubs; everywhere else the query string is ignored.
Step 4. Map the hub
Do. Complete Program.cs (new lines in green). It is now final:
cs
using Chatex.Api;
using Chatex.Api.Endpoints;
using Chatex.Api.Hubs;
using Chatex.Api.Infrastructure;
using Chatex.Core;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// AddApi first: its SignalR IChatNotifier must be registered before AddCore falls back to the no-op one.
builder.Services.AddApi(builder.Configuration);
builder.Services.AddCore(builder.Configuration);
var app = builder.Build();
app.UseForwardedHeaders();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference(o => o.AddPreferredSecuritySchemes(BearerSecuritySchemeTransformer.SchemeName));
}
// Readiness: 200 when the API can reach the database, 503 otherwise (the deploy rolls back on 503).
app.MapHealthChecks("/health").AllowAnonymous();
var api = app.MapGroup("/api").RequireAuthorization();
api.MapAuthEndpoints();
api.MapProfileEndpoints();
api.MapUserEndpoints();
api.MapChatEndpoints();
api.MapMessageEndpoints();
api.MapAttachmentEndpoints();
app.MapHub<ChatHub>("/hubs/chat");
app.Run();
/// <summary>Visible to <c>WebApplicationFactory</c> in the Api tests.</summary>
public partial class Program;MapHub<ChatHub>("/hubs/chat") makes the hub reachable; the hub's [Authorize] attribute requires a valid token for connecting. The comment above AddApi now explains the order of the two registrations.
Check
dotnet build succeeds, and the backend is complete. The SignalR client of the browser comes in topic 20; the next chapter tests the hub with the .NET client.