March 1, 2023
READING TIME2 min

TIL: Caddy's forward_auth Directive

We recently ran into an issue where — boiled down — we had two servers:

  1. A Node.js server that would authenticate API users via the Authorization header. It exposes an /auth/verify endpoint, which returns 2xx if this header is valid.
  2. A websocket server we had no control over with no authentication mechanism

How could we expose this websocket server without it being unprotected?

After researching a bit, we found Caddy has a directive called forward_auth. We could leverage this to forward all requests to our upstream node server's token verification endpoint before they're passed along (if successful) to our upstream websockets server.

Caddyfile
:9000
forward_auth {$UPSTREAM_NODE_SERVER} {
uri /auth/verify
}
reverse_proxy {$UPSTREAM_WEBSOCKETS_SERVER} {
header_up -Authorization
}

Now, by only exposing our Caddy server, we've essentially added auth to our websocket server.

FIN.

Want more?

Consider subscribing and we'll email you as soon as a new article is published.