ITLab.Template.DevPack.Middleware
Provides ASP.NET Core middleware for culture negotiation, 404 handling, unauthenticated request fallback, identity bridging and domain-based tenant resolution.
Componentes
| Tipo | Nome | Responsabilidade |
|---|---|---|
| Class | CultureMiddleware | Sets request culture from the Accept-Language header (fallback: en-US) |
| Sealed Class | DevPackIdentityContextMiddleware | Bridges HttpContext.User claims into AsyncLocalCurrentUserAccessor so ICurrentUser consumers see the authenticated user |
| Sealed Class | TenantResolutionMiddleware | Resolves the tenant from the request host and cross-checks it against the token tenant (opt-in via MultiTenancyOptions.EnableDomainValidation) |
| Sealed Class | MalformedRequestExceptionHandler | IExceptionHandler que rende falha de binding (JSON malformado, valor que não converte) como problem details 400 com errorCode Request.Malformed e propertyName (10.16.0) |
| Static Class | DevPackMalformedRequestExtensions | AddDevPackMalformedRequestProblems() — registra o handler e liga RouteHandlerOptions.ThrowOnBadRequest |
| Static Class | RateLimitPartitionKeys | ByTenantOrUser(HttpContext) — chave de partição tenant → usuário → IP para policies de Microsoft.AspNetCore.RateLimiting (10.16.0) |
| Static Class | RateLimitRejection | WriteProblem(fallback) — OnRejected que responde 429 em problem details (errorCode RateLimit.Exceeded, retryAfterSeconds) + header Retry-After |
| Sealed Class | RefuseUndefinedEnumFilter | IEndpointFilter que recusa argumento de rota/query com valor de enum não definido (400, errorCode Request.UndefinedEnumValue); preso ao grupo, cobre as rotas futuras (10.16.0) |
| Class | NotFoundMiddleware | Intercepts 404 responses and returns a structured error payload |
| Class | UnauthenticatedFallbackMiddleware | Returns 401 Unauthorized for requests that reach the pipeline without an identity |
Subnamespaces
| Namespace | Responsabilidade |
|---|---|
RequestSigning | Rota que exige JWS destacado sobre o corpo, verificado com o certificado do chamador (10.19.0) |
Como usar
// Register middleware in the correct pipeline order.
app.UseMiddleware<CultureMiddleware>();
app.UseAuthentication();
app.UseDevPackIdentityContext(); // bridge HttpContext.User → AsyncLocal
app.UseMiddleware<UnauthenticatedFallbackMiddleware>();
app.UseAuthorization();
app.UseMiddleware<NotFoundMiddleware>();
Order matters: UseAuthentication populates HttpContext.User; UseDevPackIdentityContext projects the claims into AsyncLocalCurrentUserAccessor (consumed by RoleBasedPermissionEvaluator and other ICurrentUser consumers); UseAuthorization then evaluates policies. Without the bridge, ICurrentUser.UserRoles is empty in production → 403 on every protected endpoint.
Request malformado (MalformedRequestExceptionHandler, 10.16.0)
builder.Services.AddProblemDetails();
builder.Services.AddDevPackMalformedRequestProblems();
// ...
app.UseExceptionHandler();
Sem isto, um corpo que não desserializa chega ao cliente como 400 sem corpo fora de Development — nada que
um client genérico consiga traduzir. Com isto, chega no mesmo formato de uma falha de Result
(errorCode + propertyName). Só a falha de binding (400) é tratada: 413 (corpo grande demais) e 415
(content type) mantêm o status que o framework escolheu.
Rate limiting por tenant (10.16.0)
O DevPack não embrulha o Microsoft.AspNetCore.RateLimiting — entrega a chave e a resposta:
builder.Services.AddRateLimiter(options =>
{
options.OnRejected = RateLimitRejection.WriteProblem(fallbackRetryAfter: TimeSpan.FromSeconds(10));
options.AddPolicy("per-tenant", httpContext => RateLimitPartition.GetSlidingWindowLimiter(
RateLimitPartitionKeys.ByTenantOrUser(httpContext),
_ => new SlidingWindowRateLimiterOptions
{
PermitLimit = 600,
Window = TimeSpan.FromMinutes(1),
SegmentsPerWindow = 6,
QueueLimit = 0,
}));
});
// ...
app.UseAuthentication();
app.UseDevPackIdentityContext(); // a chave lê ICurrentUser: o limiter vem DEPOIS
app.UseRateLimiter();
- Orçamento por tenant impede que um cliente barulhento esgote a capacidade dos outros; por IP, todo mundo atrás do mesmo proxy/NAT divide um balde só.
- A resposta é
429comRetry-After(do lease; senão ofallbackRetryAfter; senão omitido) e o mesmo formato de problem details de uma falha deResult. Nada foi processado — o cliente pode repetir. - O fallback por IP vale o que vale o
ForwardedHeadersdo host: nunca leia umX-Forwarded-Forenviado pelo cliente sem proxies conhecidos configurados. - Contadores ficam em memória, por réplica: com N réplicas o teto efetivo é N ×
PermitLimit.
Enum indefinido em query/rota (RefuseUndefinedEnumFilter, 10.16.0)
A ligação de query/rota aceita qualquer número para um enum (?status=99). Prenda o filtro ao grupo — não a
cada endpoint — e toda rota sob ele, inclusive as que ainda não existem, recusa o valor:
var v1 = app.NewVersionedApi().MapGroup("v{version:apiVersion}")
.AddEndpointFilter<RefuseUndefinedEnumFilter>();
Argumento nulo (filtro opcional omitido) passa; enum [Flags] é ignorado (combinação é valor válido); corpo
não passa por aqui — lá quem recusa é o StrictEnumJsonConverter.
Domain tenant resolution (TenantResolutionMiddleware)
When the host name itself carries tenant identity (acme.app.example.com → "acme"), register UseDevPackTenantResolution() after the identity bridge and before UseAuthorization:
app.UseAuthentication();
app.UseDevPackIdentityContext(); // token tenant → ICurrentUser.TenantId
app.UseDevPackTenantResolution(); // resolve host tenant + cross-check vs token
app.UseAuthorization();
The middleware is a no-op unless MultiTenancyOptions.EnableDomainValidation is true. When enabled, it resolves the host tenant via ITenantResolver, maps it to an id and validates membership through the consumer-implemented ITenantAccessValidator, then cross-checks that id against ICurrentUser.TenantId (the token tenant) — a token issued for tenant A replayed against tenant B's host is rejected. Status codes: 401 (no token tenant / unresolvable host / host-vs-token mismatch), 404 (host maps to no tenant), 403 (user has no membership). Anonymous requests and MultiTenancyOptions.ExcludedPaths pass through. The ordering after the bridge is essential — the cross-check needs the token tenant already on ICurrentUser.
O que não fazer
- Do not place
CultureMiddlewareafterUseRouting— culture must be set before route handlers execute. - Do not use
UnauthenticatedFallbackMiddlewareas a substitute for proper[Authorize]annotations. - Do not register
UseDevPackTenantResolution()beforeUseDevPackIdentityContext()— the cross-check readsICurrentUser.TenantId, which the bridge populates. Wrong order silently skips the check (token tenant always0). - Do not forget
IHttpContextAccessorwhen enabling domain resolution —DomainTenantResolveContributorresolves the request through it.
Extensão pelo produto
- Products can extend
NotFoundMiddlewareto include product-specific 404 response bodies. - Products can extend
CultureMiddlewareto resolve culture from user profile settings instead of the request header.