Lesson 3 of 9 · 25m
Middleware, Validation, and Authentication Boundaries
Compose middleware in the right order, validate transport input at the edge, and keep identity, tenancy, and authorization server-derived.
Most broken Vapor services do not lack authentication code. They have authentication scattered across handlers, helpers, and half-configured middleware until no one can say which routes are actually protected. Identity should enter once; authorization belongs close to the object.
Middleware order is behavior
app.middleware.use(ErrorMiddleware.default(environment: app.environment))
app.middleware.use(RequestIDMiddleware())
app.middleware.use(MetricsMiddleware())
let api = app.grouped("api", "v1")
let authed = api.grouped(BearerTokenAuthenticator())Error middleware belongs early enough to shape thrown errors. Request IDs should exist before logging. Authentication wraps the routes that need identity; health checks and public metadata often should not inherit it.
Validation is not authorization
struct CreateProjectRequest: Content, Validatable {
var name: String
var slug: String
static func validations(_ validations: inout Validations) {
validations.add("name", as: String.self, is: !.empty && .count(1...80))
validations.add("slug", as: String.self, is: .count(3...64))
}
}
try CreateProjectRequest.validate(content: req)
let input = try req.content.decode(CreateProjectRequest.self)Validation proves shape. It does not prove the caller may create anything in this tenant. Those are separate questions and should be tested separately.
Decode narrow DTOs
Never decode directly into a Fluent model. Models carry server-controlled fields such as IDs, ownership, timestamps, secrets, and deletion state. A request DTO admits only client-controlled fields:
struct UpdateProfileRequest: Content {
var displayName: String?
var locale: String?
}Apply it explicitly. This is how you avoid mass-assignment accidents when a crafted role or tenantID appears.
Authentication produces context; authorization checks relationships
Hash stored bearer tokens before lookup, then load only valid sessions:
guard let session = try await ApiSession.query(on: req.db)
.filter(\.$tokenHash == sha256(bearer.token))
.first(), session.isCurrentlyValid else { return }
req.auth.login(AuthenticatedUser(id: session.userID, tenantID: session.tenantID))At the object boundary, enforce the relationship:
guard project.tenantID == user.tenantID else {
throw Abort(.notFound)
}Field notes
- CORS is browser enforcement, not API authorization; curl ignores it.
- Global authentication becomes awkward as soon as health checks, webhooks, or password reset exist.
- Token expiry is not revocation when accounts are disabled or users leave tenants.
- Test tenant A against tenant B's object. One-tenant tests miss the boundary.
Was this lesson helpful?