C.W.K.
Stream
Lesson 04 of 06 · published

Perimeter vs Per-Request Auth

~15 min · middleware, perimeter, defense-in-depth

Level 0Greenhorn
0 XP0/53 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Where does the auth check happen? Two architectural patterns, with very different blast radii when something goes wrong.

PatternWhere checks liveProCon
PerimeterNetwork/proxy layer (VPN, firewall, reverse proxy)Apps don't need to know about auth at allOne layer = one mistake away from total exposure
Per-requestInside each app (middleware, route decorator)Defense in depth; bypassing one route doesn't bypass othersRepeated logic, easy to forget on a new endpoint

Solo dev reality: both, layered

This is the entire reason for the "two cheap locks" model:

  • Tailscale = perimeter — only devices in your tailnet can even reach the host. (Track 4)
  • PIN middleware = per-request — even devices in the tailnet need a session cookie to hit any non-public endpoint. (Track 5)

Where to put per-request auth

In FastAPI, Express, Flask, or any modern web framework: middleware, not per-route checks. Middleware runs before every request hits a handler, so you can't forget to add it on a new route.

Code

FastAPI middleware sketch — see Track 5 for full version·python
class PinAuthMiddleware:
    PUBLIC = {"/login", "/health", "/static"}

    async def __call__(self, request, call_next):
        path = request.url.path
        if any(path.startswith(p) for p in self.PUBLIC):
            return await call_next(request)
        if request.client.host in LOCAL_IPS:    # opt-in bypass
            return await call_next(request)
        token = request.cookies.get("session")
        if not token or not is_valid_session(token, request.client.host):
            return RedirectResponse("/login")
        return await call_next(request)

External links

Exercise

On one of your apps, count the routes. Now count how many have an explicit auth decorator. The ratio tells you whether you're middleware-first or decorator-first. If decorators dominate, write a middleware that protects everything by default and make the public routes opt out — invert the bias.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.