Documentation
¶
Overview ¶
The jwt middleware: a Signer/Verifier round trip.
middleware/jwt is the thin layer beneath the auth SDK: no providers, no user store. A Signer mints tokens, a Verifier turns "Authorization: Bearer <token>" into typed claims for the routes it guards. Reach for it when you only need to sign or verify, for example a resource server that trusts tokens issued elsewhere.
v14 default: the verifier reads the Authorization header ONLY. The ?token= query extractor is opt-in (verifier.WithQueryToken()), because tokens in URLs leak into access logs, proxy logs, browser history and Referer headers.
The signing secret comes from the JWT_SECRET environment variable; without it the example falls back to a development-only constant so it still runs.
Learn: mint tokens with a Signer, guard a router with a Verifier that reads only the Authorization header, and revoke one token through the blocklist. Before: ../api-key
Run:
JWT_SECRET=a-32-byte-or-longer-random-secret go run main.go
Try:
TOKEN=$(curl -s -X POST -H "Content-Type: application/json" \
http://localhost:8080/token -d '{"username":"makis"}' | sed 's/.*"token":"//;s/".*//') # 200, token and expires_in
curl -i http://localhost:8080/api/me # 401, no Authorization header
curl -i "http://localhost:8080/api/me?token=$TOKEN" # 401, query tokens are opt-in
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/me # 200, the claims
curl -i -H "Authorization: Bearer $TOKEN" -X POST http://localhost:8080/api/logout # 200, token invalidated
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/me # 401, blocklisted now
Next: ../sessions