APIs with Express · Chapter 15 of 29
JWT auth
By the end of this chapter you can build and check JSON Web Tokens by hand, with expiry, and guard routes by the role inside them. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The Tapri API
- 6 tasks
- Express
- In the all labs plan
The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.
Why you need this
Tapri's rider app does not keep cookies the way a browser does, and Chai Point's servers want to call the staff API from their backend. Kabir wants a header token saying who the caller is and what they may do, that any Tapri server can check without a lookup.
With chapter 14's sessions, every server needs the same session store, and every request costs a lookup. A token carrying the name and role itself is easy to fake, unless signed and checked.
What you build: 6 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
base64urlEncode and base64urlDecode: URL-safe text
Export base64urlEncode(input), which takes a string (as UTF-8) or a Buffer and returns base64url: base64 with - instead of +, _ instead of /, and no = padding. base64urlEncode('chai') is 'Y2hhaQ', and the bytes fb ff give '-_8'.
Export base64urlDecode(text), which turns base64url back into a UTF-8 string: base64urlDecode('Y2hhaQ') is 'chai'. Any text, such as 'Masala chai ☕ ₹40?', comes back the same after encoding and decoding.
- Task 2
sign: an HS256 token, with an expiry when asked
Export sign(payload, secret, { expiresIn, now }), which returns header.payload.signature: the header is the JSON {"alg":"HS256","typ":"JWT"} (in that order) in base64url, the payload is the JSON of the claims in base64url, and the signature is the HMAC-SHA256 of the first two parts joined by a dot, keyed with the secret, in base64url.
With expiresIn (in seconds), the claims are a copy of the payload plus iat, now() in whole seconds (rounded down), and exp, iat plus expiresIn: at now() = 1700000000999 with expiresIn 900, iat is 1700000000 and exp 1700000900. now() returns milliseconds and defaults to Date.now. Without expiresIn the payload is signed as it is. The payload you are given never changes.
The check signs the example payload { sub: '1234567890', name: 'John Doe', iat: 1516239022 } with 'your-256-bit-secret' and expects the well-known jwt.io example token, ending in SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c.
- Task 3
verify: refuse tampered, forged and malformed tokens
Export verify(token, secret), which returns the token's payload, for example { sub: 'ravi', role: 'staff' }, when the token is genuine.
Anything else throws an Error whose message is exactly 'Invalid token': an edited payload with the old signature, a token signed with another secret, a header with alg none and an empty signature, a signature cut short or too long, two parts or four, 'chai', '', undefined, a correctly signed token whose header says HS512, and a correctly signed token whose payload is not JSON. It never crashes with any other error.
Compare the signatures with crypto.timingSafeEqual, and check the signature before trusting anything in the token.
- Task 4
verify: refuse tokens whose time is up
verify(token, secret, { now }) takes the clock too (milliseconds, Date.now by default). When the payload has an exp and now() in whole seconds has reached it, verify throws an Error with the message 'Token expired'. A token made at T with expiresIn 900 is still good at T plus 899999 milliseconds and expired at T plus 900000.
The signature comes first: a forged token with exp 1 is 'Invalid token', not expired, and an exp moved into the future breaks the signature. A token without exp never expires.
- Task 5
requireAuth: a guard for Bearer tokens
Export requireAuth(secret, { now }), which returns a middleware. It reads the Authorization header, which must be the word Bearer, a space and a token. It verifies the token (passing now on) and puts the payload on req.user, then passes the request on.
No header, another scheme such as Basic, or Bearer with no token answers 401 with { error: 'Missing token' }. A token verify refuses answers 401 with { error: 'Invalid token' } or { error: 'Token expired' }, the message verify threw. Every 401 also sends the header WWW-Authenticate: Bearer.
- Task 6 · interview question
Interview: DELETE /menu/:id, for admins only
In createApp({ secret, now }), add three routes and use the app's now for every token.
POST /login with { name, pin } answers 200 with { token }, a token signed with sign for { sub: name, role } that expires in 15 minutes (900 seconds). A name that is not one of staff's own, or a wrong pin, answers 401 with { error: 'Wrong name or pin' }.
GET /orders, for any logged-in user, answers 200 with { user: <sub>, orders: [] }, for example { user: 'ravi', orders: [] }; without a token it is a 401 from requireAuth.
DELETE /menu/:id needs requireAuth and then the admin role: it removes the item and answers 204, so GET /menu no longer lists it. A logged-in user with another role answers 403 with { error: 'Admins only' }. A token whose role was edited to admin answers 401 and deletes nothing. Tokens from /login stop working after 15 minutes with 401 { error: 'Token expired' }.
What you will learn
- Base64url: the URL-safe text every part of a token is written in.
- A JWT: a header, a payload and a signature, and why anyone can read the payload.
- Verifying: the tokens a server must refuse, and expiry in seconds.
- Bearer tokens and roles: the Authorization header, and 401 versus 403.
More in The Tapri API
Build "JWT auth" yourself
Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.