0Pricing
Swift Academy · Lesson

Middleware and Authentication

Add cross-cutting logic and protect routes.

Middleware and Authentication is a free Swift Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Middleware?

Middleware sits between the incoming request and your route handler, able to inspect or modify both the request and the response. It is perfect for logging, CORS, error handling, and authentication.

import Vapor

The Middleware Protocol

A custom middleware conforms to AsyncMiddleware and implements respond(to:chainingTo:). You do work, then call next.respond(to:) to continue the chain.

struct LogMiddleware: AsyncMiddleware {
    func respond(to req: Request, chainingTo next: AsyncResponder) async throws -> Response {
        req.logger.info("Incoming: " + req.url.path)
        return try await next.respond(to: req)
    }
}

Registering Middleware Globally

Add middleware to app.middleware to run it for every request. Order matters — middleware runs in the order added.

app.middleware.use(LogMiddleware())

Built-in Middleware

Vapor ships useful middleware: ErrorMiddleware converts thrown errors into responses, FileMiddleware serves static files, and CORSMiddleware handles cross-origin requests.

let cors = CORSMiddleware(configuration: .default())
app.middleware.use(cors)

Route-Specific Middleware

Apply middleware to only some routes by grouping with it. Routes inside the group are protected; others are not.

let protected = app.grouped(LogMiddleware())
protected.get("dashboard") { req in "Secret dashboard" }

Authentication Concepts

Vapor's authentication system has two halves: an Authenticatable model (your user), and an Authenticator middleware that verifies credentials and stores the user on the request.

final class AppUser: Model, Content, Authenticatable {
    static let schema = "users"
    @ID(key: .id) var id: UUID?
    @Field(key: "username") var username: String
    @Field(key: "password_hash") var passwordHash: String
    init() {}
}

Writing a Basic Authenticator

An AsyncBasicAuthenticator handles HTTP Basic auth. Implement authenticate(basic:for:): look up the user, verify the password, and call req.auth.login(user) on success.

struct UserAuthenticator: AsyncBasicAuthenticator {
    func authenticate(basic: BasicAuthorization, for req: Request) async throws {
        guard let user = try await AppUser.query(on: req.db)
            .filter(\.$username == basic.username).first() else { return }
        if try Bcrypt.verify(basic.password, created: user.passwordHash) {
            req.auth.login(user)
        }
    }
}

Hashing Passwords with Bcrypt

Never store plain passwords. Vapor bundles Bcrypt to hash on signup and verify on login. Hashing is one-way; verification compares a candidate against the stored hash.

let hash = try Bcrypt.hash("s3cret")
let ok = try Bcrypt.verify("s3cret", created: hash) // true

Protecting Routes with a Guard

Combine the authenticator with AppUser.guardMiddleware(), which rejects unauthenticated requests with 401. Group protected routes behind both.

let protected = app.grouped(
    UserAuthenticator(),
    AppUser.guardMiddleware()
)
protected.get("me") { req -> String in
    let user = try req.auth.require(AppUser.self)
    return user.username
}

Reading the Authenticated User

Inside a protected handler, retrieve the logged-in user with req.auth.require(_:) (throws if absent) or req.auth.get(_:) (optional). This is how you scope data to the current user.

app.get("profile") { req -> String in
    let user = try req.auth.require(AppUser.self)
    return "Hello, " + user.username
}

Token Authentication

For APIs, bearer tokens are common. A token model conforms to ModelTokenAuthenticatable, letting Vapor verify an Authorization: Bearer ... header and load the associated user automatically.

let tokenProtected = app.grouped(
    UserToken.authenticator(),
    AppUser.guardMiddleware()
)

Quick Check: Middleware and Auth

Confirm your understanding.

Recap: Middleware and Authentication

You learned to intercept requests and secure them:

  • Middleware (AsyncMiddleware) wraps requests; register globally or per-route group.
  • Use built-ins like ErrorMiddleware and CORSMiddleware.
  • Make a user Authenticatable, write an Authenticator, and call req.auth.login.
  • Hash with Bcrypt, protect routes with guardMiddleware(), and read the user via req.auth.require.

Frequently asked questions

Is the “Middleware and Authentication” lesson free?

Yes — the full text of “Middleware and Authentication” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Middleware and Authentication”?

Add cross-cutting logic and protect routes. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Middleware and Authentication” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Routing and Request Handling
  2. Content and JSON Encoding
  3. Fluent ORM and Models
  4. Middleware and Authentication
← Back to Swift Academy