English
The composition root
Step 1. Packages and settings
Why. The composition root is the one place where the whole application is assembled: services registered, settings read, middleware ordered, endpoints mapped. In Chatex it is Program.cs plus AddApi. Before writing it, the web project needs three packages and its development settings.
Do.
powershell
dotnet add Source/Chatex.Api package Microsoft.AspNetCore.Authentication.JwtBearerpowershell
dotnet add Source/Chatex.Api package Microsoft.AspNetCore.OpenApipowershell
dotnet add Source/Chatex.Api package Scalar.AspNetCorexml
<Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<ProjectReference Include="..\Chatex.Core\Chatex.Core.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
<PackageReference Include="Scalar.AspNetCore" />
</ItemGroup>
</Project>- JwtBearer validates access tokens on every request.
- OpenApi generates an OpenAPI document — a machine-readable description of every endpoint — from the code.
- Scalar shows that document as an interactive reference where you can send requests.
The settings that the layers below read (topics 5, 7, 8) go into the development settings file; the template created both files in topic 2. Replace them:
json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}json
{
"ConnectionStrings": {
"Chatex": "Host=localhost;Port=5432;Database=chatex;Username=postgres;Password=postgres"
},
"Jwt": {
"Issuer": "chatex-dev",
"Audience": "chatex-dev",
"SigningKey": "dev-only-signing-key-change-me-in-production-0123456789"
},
"Storage": {
"RootPath": "../../.uploads"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}ConnectionStrings:Chatexpoints to the PostgreSQL container of topic 2.Jwt: issuer, audience and a signing key of at least 32 characters. This key is for development only; production reads its key from an environment variable (topic 23), so the real key never enters the repository.Storage:RootPathis relative to the API project folder:../../.uploadsis the folder.uploadsin the repository root, which.gitignoreexcludes.appsettings.jsonapplies everywhere and keeps EF Core's SQL logging quiet;appsettings.Development.jsonis merged over it whenASPNETCORE_ENVIRONMENTisDevelopment(the launch profile of topic 2 sets it).
Step 2. The OpenAPI security scheme
Why. Scalar must know that most endpoints need a bearer token, so it can show an "Authorize" field and send the token. OpenAPI documents are adjusted with transformers: one declares the bearer scheme for the document, the other marks every operation that requires authorization.
Do.
cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;
namespace Chatex.Api.Infrastructure;
/// <summary>
/// Declares the JWT bearer scheme in the OpenAPI document and marks every operation that needs a token,
/// so Scalar can send the access token.
/// </summary>
internal sealed class BearerSecuritySchemeTransformer : IOpenApiDocumentTransformer, IOpenApiOperationTransformer
{
/// <summary>The name of the bearer scheme in the OpenAPI document.</summary>
public const string SchemeName = "Bearer";
public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
{
document.Components ??= new OpenApiComponents();
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
document.Components.SecuritySchemes[SchemeName] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "The access token returned by /api/auth/login, /register or /refresh.",
};
return Task.CompletedTask;
}
public Task TransformAsync(OpenApiOperation operation, OpenApiOperationTransformerContext context, CancellationToken cancellationToken)
{
var metadata = context.Description.ActionDescriptor.EndpointMetadata;
if (metadata.OfType<IAllowAnonymous>().Any() || !metadata.OfType<IAuthorizeData>().Any())
{
return Task.CompletedTask;
}
operation.Security ??= [];
operation.Security.Add(new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference(SchemeName, context.Document)] = [],
});
return Task.CompletedTask;
}
}The operation transformer looks at the endpoint metadata: endpoints with AllowAnonymous (login, register) or without any authorization requirement get no security requirement.
Step 3. AddApi
Why. Like each layer below, the web layer registers its services in one extension method.
Do. Create DependencyInjection.cs in the root of Chatex.Api:
cs
using System.Text.Json;
using System.Text.Json.Serialization;
using Chatex.Api.Infrastructure;
using Chatex.Core.Auth;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace Chatex.Api;
public static class DependencyInjection
{
public static IServiceCollection AddApi(this IServiceCollection services, IConfiguration configuration)
{
services.ConfigureHttpJsonOptions(o =>
o.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)));
services.AddProblemDetails();
// 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),
};
});
services.AddAuthorization();
services.AddOpenApi(o =>
{
o.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
o.AddOperationTransformer<BearerSecuritySchemeTransformer>();
});
return services;
}
}ConfigureHttpJsonOptionswithJsonStringEnumConverter(JsonNamingPolicy.CamelCase)writes enumerations as camelCase strings:"type": "group","myRole": "owner". Numbers would be meaningless to a client and break when the enumeration changes.AddProblemDetailsmakes the framework's own errors (404 for an unknown route, 500 for an unhandled exception) Problem Details too.ThrowOnBadRequest = false: a malformed JSON body answers400in every environment instead of throwing in Development.- JWT bearer:
AddAuthentication(...).AddJwtBearer()registers the scheme; the options are configured fromJwtOptionsof topic 8 throughAddOptions<JwtBearerOptions>().Configure<IOptions<JwtOptions>>(...), so the validation uses exactly the settings that signed the token:MapInboundClaims = falsekeeps the claim names of the token (sub,unique_name) instead of translating them to long Microsoft URIs;ValidIssuer,ValidAudience,IssuerSigningKeyfrom the same settings andCreateSigningKeyas the token service;ValidAlgorithms = [HmacSha256]refuses tokens signed with any other algorithm;ClockSkewof 30 seconds tolerates small clock differences between servers (the default is 5 minutes).
AddOpenApiwith the two transformers.
Step 4. Program.cs
Do. Replace the template's Program.cs:
cs
using Chatex.Api;
using Chatex.Api.Endpoints;
using Chatex.Api.Infrastructure;
using Chatex.Core;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddApi(builder.Configuration);
builder.Services.AddCore(builder.Configuration);
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseAuthentication();
app.UseAuthorization();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference(o => o.AddPreferredSecuritySchemes(BearerSecuritySchemeTransformer.SchemeName));
}
var api = app.MapGroup("/api").RequireAuthorization();
api.MapAuthEndpoints();
api.MapProfileEndpoints();
api.MapUserEndpoints();
api.MapChatEndpoints();
api.MapMessageEndpoints();
app.Run();
/// <summary>Visible to <c>WebApplicationFactory</c> in the Api tests.</summary>
public partial class Program;- Top-level statements: the file is the program;
builderbuilds the host,appis the running application. AddApithenAddCore: the order matters from topic 14 on (the SignalR notifier must be registered first); keep it from the start.- The middleware pipeline runs in the written order for every request:
UseExceptionHandlerturns unhandled exceptions into a 500 Problem Details response without a stack trace;UseStatusCodePagesgives empty error responses (such as a 401 from the authentication middleware) a Problem Details body;UseAuthenticationreads the bearer token and createsHttpContext.User;UseAuthorizationenforcesRequireAuthorization.
- OpenAPI and Scalar only in Development: production does not advertise its API surface.
MapGroup("/api").RequireAuthorization()— every endpoint under/apirequires a valid token unless it saysAllowAnonymous. Secure by default: a new endpoint someone forgets to protect is protected anyway.public partial class Program;makes the generatedProgramclass visible to the test project'sWebApplicationFactory<Program>(Testing over HTTP).
Step 5. Run the API
Do. Start the database and apply the migrations, then run the API:
powershell
./Run.ps1 dbpowershell
./Run.ps1 apiCheck
Open http://localhost:5214/scalar. The reference lists the groups Auth, Profile, Users, Chats and Messages.
Open Auth → Register and send
json{ "userName": "alice", "email": "[email protected]", "password": "Passw0rd!", "displayName": "Alice" }The answer is
200withaccessToken,accessTokenExpiresAtanduser, and aSet-Cookieheaderchatex_refresh=…; path=/api/auth; secure; samesite=strict; httponly.Copy the
accessToken, paste it into the authentication field of Scalar, and send Profile → GetMyProfile:200with your profile. Without the token:401with a Problem Details body.Send Auth → Login with a wrong password:
401andjson{ "title": "Unauthorized", "status": 401, "detail": "The user name, email or password is wrong.", "code": "invalid_credentials", … }
The reference repository also has a file of sample requests for Visual Studio, Rider and VS Code (with the REST Client extension). Copy it into the API project:
powershell
Invoke-WebRequest https://raw.githubusercontent.com/musicvano/Chatex/27c83c6932b902c8d8dcef01e30a3dd32c5be05f/Source/Chatex.Api/Chatex.Api.http -OutFile Source/Chatex.Api/Chatex.Api.httphttp
### Sample requests for the Chatex API.
### Run the API with `dotnet run --project Source/Chatex.Api --launch-profile http`,
### then send "Register" (or "Login"); later requests reuse its access token.
@host = http://localhost:5214
### Register
# @name register
POST {{host}}/api/auth/register
Content-Type: application/json
# ...
### My profile
GET {{host}}/api/me
Authorization: Bearer {{register.response.body.accessToken}}
# ...# @name register names a request, and a later request reuses a value of its response with the double-brace expression register.response.body.accessToken that you can see in the listing. Run "Register" first, then the others. The upload request at the end works from topic 13.