Request Pipeline
Trực quan hóa hành trình của một HTTP request qua các middleware
Interactive Pipeline Visualizer
Chọn một kịch bản và nhấn "GỬI REQUEST" để xem request di chuyển qua từng middleware trong ASP.NET Core pipeline.
Unauthorized
Forbidden
Middleware Pipeline Chi Tiết
Mỗi middleware trong pipeline có một nhiệm vụ cụ thể. Request đi qua từng middleware theo thứ tự, và bất kỳ middleware nào cũng có thể short-circuit (dừng pipeline sớm) nếu cần.
HttpContext.
ClaimsPrincipal, và gán vào HttpContext.User.
HttpContext.User
sẽ là anonymous. Nếu endpoint yêu cầu authentication, Authorization middleware
sẽ trả 401 Unauthorized.
[Authorize]),
nếu có thì đánh giá policies, roles, và claims của user
hiện tại.
Challenge vs Forbid: 401 vs 403
Hai kết quả thất bại của authorization có ý nghĩa rất khác nhau. Hiểu đúng sự khác biệt giúp bạn debug và thiết kế security flow chính xác.
JWT / API: trả về 401 JSON response.
JWT / API: trả về 403 JSON response.
Thêm Custom Middleware vào Pipeline
Bạn có thể chèn middleware tùy chỉnh vào bất kỳ vị trí nào trong pipeline. Vị trí đặt middleware quyết định nó có quyền truy cập thông tin gì.
// Middleware log mọi request (đặt TRƯỚC auth) app.Use(async (context, next) => { var start = DateTime.UtcNow; Console.WriteLine($"▶ {context.Request.Method} {context.Request.Path}"); await next(); // Gọi middleware tiếp theo var elapsed = DateTime.UtcNow - start; Console.WriteLine($"◀ {context.Response.StatusCode} ({elapsed.TotalMilliseconds}ms)"); }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); // Middleware kiểm tra thêm sau authorization (ví dụ: rate limiting) app.Use(async (context, next) => { if (IsRateLimited(context)) { context.Response.StatusCode = 429; // Too Many Requests return; // Short-circuit — không gọi next() } await next(); }); app.MapControllers();
Pipeline với Custom Middleware
Middleware tùy chỉnh (màu vàng) có thể được chèn vào trước hoặc sau các built-in middleware:
await next() để chuyển request đến middleware tiếp theo.
Nếu không gọi next(), pipeline sẽ bị short-circuit
— các middleware phía sau sẽ không được thực thi.
Đây là cách bạn trả về response sớm (ví dụ: 429,
401).
Tại sao thứ tự Middleware quan trọng?
Authorization middleware cần biết (1) endpoint nào đã được chọn (từ Routing) và (2) user là ai (từ Authentication). Nếu đặt sai thứ tự, Authorization sẽ luôn thấy user chưa authenticated và từ chối mọi request.
UseAuthorization() chạy trước
UseAuthentication() nên HttpContext.User luôn là anonymous. Kết
quả: mọi request đến endpoint có [Authorize] sẽ bị
trả về 401, dù user có token hợp lệ.