Українська
Від сервісів до браузерів
Крок 1. Сповіщувач
Навіщо. У темі 10 бізнес-рівень оголосив IChatNotifier і викликав його після кожного коміту; досі NullChatNotifier ковтав події. Веб-рівень реалізує інтерфейс через SignalR: кожна подія іде до групи свого чату (рис. 14.3).
Рис. 14.3. Одне повідомлення від початку до кінця
Alice отримує власне повідомлення двічі – як HTTP-відповідь і як подію, у будь-якому порядку. Сховище Angular об’єднує повідомлення за ідентифікатором (тема 19), тож це безпечно й залишає сервер простим: немає логіки «усім, крім відправника», яка зламалася б, коли в Alice відкрита друга вкладка.
Що зробити.
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>надсилає ззовні хаба;hub.Clients.Group(name)повертаєIChatClient, тож події – це типізовані виклики на кшталт.MessageCreated(message).- Зміни складу учасників торкаються груп. Відкриті з’єднання нового учасника додаються до групи перед надсиланням
MembersAdded, тож новий учасник отримує цю подію й усі наступні без перепідключення. Вилучений учасник отримуєMemberRemovedпершим – щоб клієнт про це дізнався, – і лише потім його виводять із групи. - Сповіщувач – singleton: контекст хаба й трекер також singleton.
Крок 2. Токени для з’єднань WebSocket
Навіщо. Браузер не може встановити заголовок Authorization для запиту WebSocket чи Server-Sent Events. Тому клієнт SignalR для JavaScript надсилає токен доступу в рядку запиту: /hubs/chat?access_token=…. Обробник JWT має брати його звідти – але лише для шляхів хаба: токени в URL потрапляють до журналів сервера й історії браузера, тож жодна інша кінцева точка не повинна їх приймати.
Крок 3. Зареєструйте SignalR
Що зробити. Завершіть AddApi (нові рядки позначено зеленим). Метод і його коментар тепер остаточні:
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(...)із тим самим перетворювачем перелічень у camelCase, що й для HTTP, тожChatDtoвиглядає однаково у відповіді й у події.PresenceOptions(пільговий період), трекер і сервіс присутності як singleton;SubClaimUserIdProviderзамінює типовийIUserIdProviderSignalR.AddSingleton<IChatNotifier, SignalRChatNotifier>()– ось чомуAddApiмає виконуватися передAddCore:AddCoreреєструєNullChatNotifierчерезTryAddSingleton, який тепер знаходить сповіщувач і нічого не робить (тема 10).bearer.Events.OnMessageReceivedбере токен зaccess_token, коли шлях починається з/hubs; усюди інде рядок запиту ігнорується.
Крок 4. Зіставте хаб
Що зробити. Завершіть Program.cs (нові рядки позначено зеленим). Тепер він остаточний:
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") робить хаб досяжним; атрибут [Authorize] хаба вимагає чинного токена для підключення. Коментар над AddApi тепер пояснює порядок двох реєстрацій.
Перевірка
dotnet build проходить успішно, серверна частина завершена. Клієнт SignalR для браузера з’явиться в темі 20; наступний розділ тестує хаб клієнтом .NET.