Skip to lesson

Tokens in headers as an alternative

ShopLite also has a mobile app. An app has no browser cookie jar, so the server needs a login credential that the app can add to each request by itself and that the server can check without a session record.

Login returns a token; the client sends Authorization: Bearer

A bearer token is a string that lets in whoever holds ("bears") it, like a printed concert ticket. The client gets it at login and sends it in the Authorization: Bearer header.

Log in to the token API and read the JSON it returns, then call a protected endpoint with and without the token.

Example 1 · Login returns a token

Runs in: the demo login server on localhost:8080

Terminal
curl -d "username=asha" -d "password=campus123" http://localhost:8080/api/login
Sample output
{"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MjExODM1MywiZXhwIjoxNzkyMTE5MjUzfQ.4VA14t1RT7sXm47SSJHSynEZ3Ctn-76Pxe0NJl00JNg","tokenType":"Bearer","expiresIn":900,"refreshToken":"ogijCI4M_CstKUoYvkjwBORAfnl6VOmI"}

What this code does

  • The token API answers with JSON instead of a cookie: accessToken is the JWT, tokenType says how to send it, and expiresIn is its lifetime in seconds (900 = 15 minutes).
  • refreshToken is explained in the last section; ignore it for now.

Example 2 · The same endpoint without and with the token

Runs in: the demo login server on localhost:8080

Terminal
curl -i http://localhost:8080/api/meTOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MjExODM1MywiZXhwIjoxNzkyMTE5MjUzfQ.4VA14t1RT7sXm47SSJHSynEZ3Ctn-76Pxe0NJl00JNg"curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/me
Sample output
$ curl -i http://localhost:8080/api/me
HTTP/1.1 401 Unauthorized
Content-Type: application/json
Content-Length: 33
Connection: close
Date: Fri, 16 Oct 2026 02:39:15 GMT
WWW-Authenticate: Bearer

{"error":"Missing bearer token"}

$ TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MjExODM1MywiZXhwIjoxNzkyMTE5MjUzfQ.4VA14t1RT7sXm47SSJHSynEZ3Ctn-76Pxe0NJl00JNg"

$ curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/me
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 53
Connection: close
Date: Fri, 16 Oct 2026 02:39:16 GMT

{"user":"asha","name":"Asha Verma","role":"student"}

What this code does

  • With no Authorization header the server answers 401 and WWW-Authenticate: Bearer, saying a bearer token is expected.
  • With the header the server checks the signature and expiry, reads sub, name and role from the payload, and answers 200 without any session lookup.

The client sends the token in the Authorization request header, using the Bearer scheme: Authorization: Bearer eyJhbGci.... A request with no token, or a bad one, gets 401 Unauthorized.

Nothing is set as a cookie: the client decides where to keep the token and must add the header itself.

To avoid pasting the token into every command, store it in a shell variable: TOKEN="eyJ..." in Git Bash or macOS Terminal, $TOKEN = "eyJ..." in PowerShell (where you also type curl.exe). The curl line itself is the same.

What a JWT looks like: header, payload, signature

A JWT (JSON Web Token) is a token made of three Base64URL parts joined by dots: header.payload.signature. Anyone can read it, but only the holder of the secret key can sign it.

Split the token from the login at its two dots and decode the first two parts.

Example 3 · Taking a real JWT apart

Text
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MjExODM1MywiZXhwIjoxNzkyMTE5MjUzfQ.4VA14t1RT7sXm47SSJHSynEZ3Ctn-76Pxe0NJl00JNg
Decoded
Header:    {"alg":"HS256","typ":"JWT"}
Payload:   {"sub":"asha","name":"Asha Verma","role":"student","iat":1792118353,"exp":1792119253}
Signature: 32 bytes of HMAC-SHA256, not readable text

iat 1792118353 = 2026-10-16T02:39:13Z
exp 1792119253 = 2026-10-16T02:54:13Z

What this code does

  • This is the token from Example 1, split at its two dots. Decoding the first two parts needs no key: any Base64URL decoder (or a site such as jwt.io, for test tokens only) shows the same JSON.
  • exp minus iat is 900 seconds, the 15 minutes in expiresIn. The payload is readable by anyone who holds the token, which is why it contains no secrets.

Example 4 · A changed payload breaks the signature

Runs in: the demo login server on localhost:8080

Terminal
# The payload was decoded, "role":"student" was changed to "role":"admin",# and it was encoded again. The signature part was left as it was.TAMPERED="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE3OTIxMTgzNTMsImV4cCI6MTc5MjExOTI1M30.4VA14t1RT7sXm47SSJHSynEZ3Ctn-76Pxe0NJl00JNg"curl -i -H "Authorization: Bearer $TAMPERED" http://localhost:8080/api/me
Sample output
$ TAMPERED="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE3OTIxMTgzNTMsImV4cCI6MTc5MjExOTI1M30.4VA14t1RT7sXm47SSJHSynEZ3Ctn-76Pxe0NJl00JNg"

$ curl -i -H "Authorization: Bearer $TAMPERED" http://localhost:8080/api/me
HTTP/1.1 401 Unauthorized
Content-Type: application/json
Content-Length: 37
Connection: close
Date: Fri, 16 Oct 2026 02:39:18 GMT
WWW-Authenticate: Bearer error="invalid_token", error_description="Signature does not match"

{"error":"Signature does not match"}

What this code does

  • The server recomputed the signature over the new header and payload with its secret key. It did not match the signature in the token, so the request was refused with 401 and error="invalid_token".
  • Without the key, nobody can make a valid signature for a changed payload. That is what "signed" buys you, even though anyone can read the payload.

Base64URL is a way to write any bytes with only letters, digits, - and _. It is encoding, not encryption: anyone can decode the header and payload back to JSON. The header names the signing algorithm. The payload holds claims, facts about the user: sub (the user id), iat (issued at) and exp (expires at), both in Unix seconds, plus any extra fields. The signature is computed from the header, the payload and a secret key only the server knows; here the algorithm is HS256 (HMAC with SHA-256).

So a JWT proves two things: this server issued it, and nobody has changed it since. It hides nothing, so never put passwords, phone numbers or other private data in the payload.

Predict the output

Will the server accept the token?

Pick the answer the API gives. The access token lasts 15 minutes.

Round 1 of 3

A valid token, sent 2 minutes after login.

GET /api/me
Authorization: Bearer <header>.<payload>.<signature>

Sessions versus tokens

Both approaches send a credential with every request; they differ in where the state lives and what follows from that.

  • Where state lives: a session keeps user data on the server, found by an id. A JWT carries the claims itself, so any server with the key can check it without a lookup.
  • Logout: deleting a session ends it at once. A JWT stays valid until exp, unless the server keeps a block list, which brings back server-side state.
  • Scaling: sessions need a shared store when there are many servers. JWTs need only the key on every server.
  • Clients: browsers handle cookies automatically. Mobile apps, command-line tools and other servers find it simpler to send a header, and a token works across different domains.
Neither is always better. Many web apps use cookie sessions for the browser and tokens for their mobile app and public API.

Where clients keep tokens, and the risks of each place

A bearer token is as powerful as a password for as long as it is valid, so where the client keeps it matters.

  • Memory (a variable in the page's script): hard to steal, but lost when the page is refreshed.
  • localStorage (browser storage that scripts can read): survives refresh, but any script on the page can read it, so one XSS bug (cross-site scripting: an attacker's script running in your page) leaks the token.
  • An HttpOnly cookie: scripts cannot read it, but the browser now sends it automatically, so CSRF protection is needed again.
  • Mobile apps: the phone's secure storage (Keychain on iOS, Keystore on Android), never a plain file.

Find the bug

Find the unsafe token handling

Click the line that puts the token in a risky place.

Which line leaks the token into history and server logs?

Round 1 of 3
Never put tokens in URLs (?token=...): URLs end up in browser history, server logs and shared links. Never write tokens to logs.

Expiry and refresh tokens

A refresh token is a long-lived token sent only to a refresh endpoint to get a new access token, without asking for the password again.

Let the 15-minute access token expire, then use the refresh token to get a new pair.

Example 5 · An expired access token, and a refresh

Runs in: the demo login server on localhost:8080

Terminal
# REFRESH holds the refreshToken from the login reply in Example 1.# 16 minutes after login, the access token has expired:curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/me# Trade the refresh token for new tokens:curl -d "refreshToken=$REFRESH" http://localhost:8080/api/refreshTOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MjExOTMxOSwiZXhwIjoxNzkyMTIwMjE5fQ.oo4dTW5_QAxy96OrDV8CGUrzHuL5Ix9_2Il56wRqU7k"curl -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/me# The old refresh token was used up:curl -d "refreshToken=$REFRESH" http://localhost:8080/api/refresh
Sample output
$ curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/me
HTTP/1.1 401 Unauthorized
Content-Type: application/json
Content-Length: 26
Connection: close
Date: Fri, 16 Oct 2026 02:55:18 GMT
WWW-Authenticate: Bearer error="invalid_token", error_description="Token expired"

{"error":"Token expired"}

$ curl -d "refreshToken=$REFRESH" http://localhost:8080/api/refresh
{"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MjExOTMxOSwiZXhwIjoxNzkyMTIwMjE5fQ.oo4dTW5_QAxy96OrDV8CGUrzHuL5Ix9_2Il56wRqU7k","tokenType":"Bearer","expiresIn":900,"refreshToken":"rMK_pHcf3CYZNLJIUhXwPiBZioQqAONJ"}

$ TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MjExOTMxOSwiZXhwIjoxNzkyMTIwMjE5fQ.oo4dTW5_QAxy96OrDV8CGUrzHuL5Ix9_2Il56wRqU7k"

$ curl -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/me
{"user":"asha","name":"Asha Verma","role":"student"}

$ curl -d "refreshToken=$REFRESH" http://localhost:8080/api/refresh
{"error":"Refresh token is not valid"}

What this code does

  • After 15 minutes the same token gets 401 with Token expired. The client does not ask for the password; it sends the refresh token to /api/refresh and gets a new access token and a new refresh token.
  • Sending the old refresh token again fails. This is refresh token rotation: each refresh token works once.

The access token sent on every request is kept short-lived, often 5 to 15 minutes, so a stolen one is useful only briefly. The server stores refresh tokens, so it can cancel them at logout.

Many servers also use refresh token rotation: every refresh returns a new refresh token and cancels the old one, so a stolen refresh token stops working as soon as either side uses it. A later section of the course builds this flow for real.

Order of execution

Put the refresh flow in order

Tap the steps in the order they happen.

Next step

Check your understanding

12 quick questions