Swift Academy · Lesson

Middleware and Authentication

Add cross-cutting logic and protect routes.

Lesson 4 of 413 steps

Middleware and Authentication is a free Swift Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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.
Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Middleware and Authentication” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Middleware and Authentication”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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