Explain it simply
A bearer token in plain language
Bearer means 'the one who holds it'. A bearer token is an entry pass that works for whoever is holding it, like a cinema ticket: the usher does not ask whose name it was bought under. After a successful login the server issues a token, and the client attaches it to every later request in the Authorization header.
A JWT (JSON Web Token) is the most common way to format such a token. It is like a pass with 'this is u_1, valid for 15 minutes' written on it and stamped with the server's seal. The server can verify the seal without asking a database, so it learns who is calling from the request alone. But a seal is not a cover: the text stays readable to anyone.
Problem → Why → Solution
The problem: reading the payload and trusting it
A request arrives with Authorization: Bearer eyJ... You decode the middle part of the token, see roles: ['user'], and accept it as it is. A user opens the payload in an online JWT decoder, changes roles to ['admin'], encodes it again and sends it. Nobody checks the signature, so your server hands out admin rights.
// BROKEN: reads the claims but never verifies the signature
function currentUser(authorizationHeader) {
const token = authorizationHeader.replace("Bearer ", "");
const payload = token.split(".")[1];
return JSON.parse(Buffer.from(payload, "base64url").toString());
}
const user = currentUser(req.headers.authorization);
if (user.roles.includes("admin")) {
showAdminPanel(); // anyone can edit the payload and send "roles": ["admin"]
}Signed does not mean encrypted
A JWT is signed so the server can detect changes, not to keep anyone from reading it. That protection only works if the server recomputes the signature with its secret, or checks it with the issuer's public key. Anything you can read you can also edit, and the signature is the only thing that stops an edited token from being accepted.
Core concept: sign it, verify it, let it expire
A bearer token travels as Authorization: Bearer <token> (RFC 6750). With this scheme the caller proves nothing beyond holding the token, so a thief can use it just as well. That is why HTTPS is mandatory and token lifetimes must be short. Unlike an API key, which names an application, a token usually represents one logged-in user's session.
A JWT has three parts separated by dots: header, payload and signature. The header names the algorithm (alg) and the token type (typ). The payload carries claims such as sub (who), iat (issued at) and exp (expires at). With HS256 the signature is HMAC-SHA256(header + '.' + payload, secret). Every part is base64url-encoded, a URL-safe variant of base64 that swaps + and / for - and _; it is formatting, not encryption.
On the server, check in order: are there three parts, is the header's alg the algorithm you expect (never trust what the token says about itself), does the recomputed signature match in constant time, and only then is exp (and iss and aud, if used) still valid. Only after all of that do the claims deserve trust. HS256 signs and verifies with one shared secret, while RS256 signs with a private key and verifies with a public key, so many services can verify tokens without being able to issue them.
On failure, answer 401 with a WWW-Authenticate: Bearer error="invalid_token" challenge, as RFC 6750 describes. If no token was sent at all, the challenge is just Bearer realm="api" with no error. A JWT is stateless, so it is hard to revoke before exp, which is why access tokens usually live for minutes and a refresh token is used to get the next one.
| Claim | Meaning |
|---|---|
| sub | Which user (or client) the token was issued for |
| iat / exp | Issue time and expiry time, counted in seconds since 1970 |
| iss / aud | Which server issued it and which API it is meant for |
- Login: server signs header + payload
- Client stores the token (short-lived)
- Each call: Authorization: Bearer <token>
- Server re-computes signature, checks exp
- Valid: trust the claims; else 401
The signature proves the token was not altered; it does not hide the payload.
General pattern
Authorization: Bearer <header>.<payload>.<signature>
header = base64url({"alg":"HS256","typ":"JWT"})
payload = base64url({"sub":"...","exp":<unix seconds>})
signature = base64url(HMAC-SHA256(header + "." + payload, secret))The token travels in a single header. The signature is computed over the first two parts with the secret, so changing even one character stops it matching.
Worked example: build a JWT and verify it yourself
The script builds an HS256 token with Node's crypto module. It first decodes the header and payload without any secret, which proves that anyone can read them. Then it calls a local server with a Bearer header four ways: a valid token, a token whose payload was edited to say admin, no header at all, and an expired token.
The secret and the tokens are demo values and work nowhere real. In production, use a maintained library such as jose instead of writing this yourself; the script exists so you can see the parts. The clock is fixed, so the output is identical on every run.
import http from "node:http";
import crypto from "node:crypto";
const SECRET = "demo-signing-secret-not-for-production";
const encode = (value) => Buffer.from(value).toString("base64url");
const sign = (data) =>
crypto.createHmac("sha256", SECRET).update(data).digest("base64url");
function createToken(claims) {
const header = encode(JSON.stringify({ alg: "HS256", typ: "JWT" }));
const payload = encode(JSON.stringify(claims));
return `${header}.${payload}.${sign(`${header}.${payload}`)}`;
}
let now = 1_700_000_000; // a fixed "now" in Unix seconds, so the output repeats
function verifyToken(token) {
const parts = token.split(".");
if (parts.length !== 3) return { ok: false, reason: "malformed" };
const [header, payload, signature] = parts;
if (JSON.parse(Buffer.from(header, "base64url")).alg !== "HS256") {
return { ok: false, reason: "unexpected_algorithm" }; // never trust the token's alg
}
const expected = Buffer.from(sign(`${header}.${payload}`));
const given = Buffer.from(signature);
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) {
return { ok: false, reason: "invalid_signature" };
}
const claims = JSON.parse(Buffer.from(payload, "base64url"));
if (claims.exp <= now) return { ok: false, reason: "expired" };
return { ok: true, claims };
}
const server = http.createServer((req, res) => {
const reply = (status, body, headers = {}) => {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(body));
};
const [scheme, token] = (req.headers.authorization ?? "").split(" ");
if (scheme?.toLowerCase() !== "bearer" || !token) {
const challenge = { "WWW-Authenticate": 'Bearer realm="api"' };
return reply(401, { error: "missing_token" }, challenge);
}
const result = verifyToken(token);
if (!result.ok) {
const challenge = 'Bearer realm="api", error="invalid_token"';
return reply(401, { error: result.reason }, { "WWW-Authenticate": challenge });
}
const { sub, email, roles } = result.claims;
reply(200, { id: sub, email, roles });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
async function getMe(label, authorization) {
const headers = authorization ? { Authorization: authorization } : {};
const res = await fetch(`${base}/v1/me`, { headers });
console.log(`${label.padEnd(16)} ${res.status} ${await res.text()}`);
}
const claims = { sub: "u_1", email: "alice@example.com", roles: ["user"] };
const token = createToken({ ...claims, iat: now, exp: now + 900 });
const [header, payload, signature] = token.split(".");
console.log("header :", Buffer.from(header, "base64url").toString());
console.log("payload:", Buffer.from(payload, "base64url").toString());
await getMe("valid token", `Bearer ${token}`);
const forgedClaims = { ...claims, roles: ["admin"], iat: now, exp: now + 900 };
const forged = [header, encode(JSON.stringify(forgedClaims)), signature].join(".");
await getMe("edited payload", `Bearer ${forged}`);
await getMe("no header", undefined);
now += 1000; // 1000 seconds later, the 900-second token is past its exp
await getMe("after expiry", `Bearer ${token}`);
server.close();Code breakdown
- Encode the parts
const encode = (value) => Buffer.from(value).toString("base64url");JSON text becomes bytes and then a base64url string. There is no = padding and none of the + or / characters that cause trouble in URLs.
- Sign
return `${header}.${payload}.${sign(`${header}.${payload}`)}`;The token is header.payload.signature. The signature is computed over the first two parts joined by a dot, so editing either one breaks the match.
- Pin the algorithm
if (JSON.parse(Buffer.from(header, "base64url")).alg !== "HS256") {Whatever algorithm the token's header claims, the server accepts only HS256. Some early JWT libraries could be tricked with alg none (no signature at all), which is why this check exists.
- Verify the signature
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) {The server recomputes the signature and compares it with the one that arrived in constant time. timingSafeEqual throws on unequal lengths, so the lengths are checked first.
- Check exp
if (claims.exp <= now) return { ok: false, reason: "expired" };A correct signature is not enough: once exp has passed the token is dead. Both exp and now count seconds, so they can be compared directly.
- Tamper on purpose
const forged = [header, encode(JSON.stringify(forgedClaims)), signature].join(".");The payload is replaced with roles: ['admin'] while the old signature is reused. Because the payload changed, the signature no longer matches and the server rejects it as invalid_signature.
header : {"alg":"HS256","typ":"JWT"}
payload: {"sub":"u_1","email":"alice@example.com","roles":["user"],"iat":1700000000,"exp":1700000900}
valid token 200 {"id":"u_1","email":"alice@example.com","roles":["user"]}
edited payload 401 {"error":"invalid_signature"}
no header 401 {"error":"missing_token"}
after expiry 401 {"error":"expired"}- Read the Authorization header
- Split into header, payload, signature
- Check the algorithm and the signature
- Check exp (and iss, aud)
- Trust the claims and run the handler
No header
401 + Bearer realm
Bad signature or expired
401 + error=invalid_token
Everything checks out
200 OK
exp is seconds, and base64url is not base64
Times in a JWT count seconds since 1970, while JavaScript's Date.now() counts milliseconds. Mixing the two makes every token look expired, or look like it never expires. The script below shows the right conversion next to the wrong one, and also shows how base64 and base64url differ.
const exp = 1700000900; // a JWT exp claim counts SECONDS since 1970
console.log(new Date(exp * 1000).toISOString()); // correct: convert to milliseconds
console.log(new Date(exp).toISOString()); // bug: treated as milliseconds
// base64 uses + and /, base64url uses - and _ so a token fits in a URL or header
const bytes = Buffer.from([251, 255, 254]);
console.log(bytes.toString("base64"));
console.log(bytes.toString("base64url"));The first line shows exp 1700000900 correctly, as a date in November 2023. The second treats the same number as milliseconds and lands in January 1970. The last two lines show the same bytes as +//+ in base64 and -__- in base64url.
HS256 or RS256?
| Algorithm | Who can create tokens | Who can verify them |
|---|---|---|
| HS256 (shared secret) | Anyone who knows the secret | Anyone who knows the secret |
| RS256 (key pair) | Only the holder of the private key | Anyone who has the public key |
When one service both issues and checks tokens, HS256 is the simpler choice. When one auth server issues tokens and many microservices must check them, pick RS256, so services receive only a public key and never a secret. Either way, the verifying code decides which algorithm is acceptable.
Where does the client keep the token?
| Storage | Readable by page JavaScript? | Main risk |
|---|---|---|
| A JavaScript variable (memory) | Yes, but only that page's code | Lost when the page reloads |
| HttpOnly cookie | No | CSRF, so it needs SameSite and a CSRF defence |
| localStorage | Yes | Any XSS bug can steal the token |
There is no single perfect answer, because every option trades one risk for another. Whichever you choose, keep the token short-lived, defend against XSS, and do not load scripts from sources you do not trust.
In real projects
Bearer tokens in real projects
A login endpoint checks an email and password and returns an access token, often a JWT, together with a refresh token. Single-page apps, mobile apps and other services put the access token in the Authorization header when they call the API. A gateway or middleware verifies it and attaches sub and roles to the request, so handlers know who is calling.
- Identity providers such as Auth0, Keycloak, Amazon Cognito or Firebase Auth issue the JWTs, so your API only has to verify them against the provider's public key.
- In production, use a maintained library such as jose and always check iss, aud and exp. Allowing a few seconds of leeway for clock drift is common.
- Keep access tokens to a few minutes, store the refresh token somewhere more protected, and revoke the refresh token on the server at logout.
Common mistakes
Common mistakes with bearer tokens and JWTs
Decoding the payload without verifying
Running atob or Buffer.from on the payload proves nothing. Decoding is not verifying: always check the signature and exp before believing a claim.
Putting secrets in the payload
Do not put passwords, API keys or personal data in the payload. Anyone holding the token, any proxy and anyone reading logs can read it. Keep to identifiers such as a user id.
Mixing up seconds and milliseconds
exp is in seconds. Writing exp > Date.now() compares against a number about a thousand times larger, so every token looks expired. Convert with Date.now() / 1000 or exp * 1000.
Tokens that live too long
A JWT valid for months stays useful to a thief for weeks, and because it is stateless it is hard to revoke. Keep access tokens to minutes and make clients refresh them.
Best practices
Best practices
- Verify first, trust the claims after, and choose the algorithm in your own code.
- Send tokens only over HTTPS and keep access tokens to a few minutes.
- Put only information that is fine to be public in the payload.
- Answer with WWW-Authenticate and error="invalid_token", and log why a token failed, but never the whole token.
Mini challenge
Mini challenge: a token checker with issuer and audience
Write issueToken to create an HS256 token and checkToken to verify one. Besides the signature, checkToken must verify that the issuer (iss) is auth.example.com, that the audience (aud) matches your API's name, and that exp has not passed; then try it in six situations and print the results.
- Build the token from base64url parts and sign it with crypto.createHmac
- Compare signatures with timingSafeEqual without throwing on unequal lengths
- On failure return one reason: malformed, bad_signature, wrong_issuer, wrong_audience or expired
- Try six situations and print one line for each
import crypto from "node:crypto";
// TODO: a secret, the expected issuer, and two helpers: b64(object) and mac(text)
// TODO: issueToken(claims) -> "header.payload.signature" (HS256, iss added for you)
// TODO: checkToken(token, { audience, now })
// -> { ok: true, claims } or { ok: false, reason }
// reasons, in order: malformed, bad_signature, wrong_issuer, wrong_audience, expired
// TODO: build one good token, then check it in six situations and print one line each:
// valid, other audience, after expiry, foreign issuer, cut signature, two-part stringExpected: valid prints ok, other audience prints wrong_audience, after expiry prints expired, foreign issuer prints wrong_issuer, cut signature prints bad_signature and the two-part string prints malformed.
Show hint
Verify the signature first and never read claims from a token that failed it. To test a foreign issuer, spread claims after the default iss in issueToken so a caller can override it.
Show solution
import crypto from "node:crypto";
const KEY = "challenge-secret-not-for-production";
const ISSUER = "auth.example.com";
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const mac = (text) => crypto.createHmac("sha256", KEY).update(text).digest("base64url");
function issueToken(claims) {
const head = b64({ alg: "HS256", typ: "JWT" });
const body = b64({ iss: ISSUER, ...claims });
return `${head}.${body}.${mac(`${head}.${body}`)}`;
}
function checkToken(token, { audience, now }) {
const parts = token.split(".");
if (parts.length !== 3) return { ok: false, reason: "malformed" };
const [head, body, sig] = parts;
const good = Buffer.from(mac(`${head}.${body}`));
const got = Buffer.from(sig);
if (good.length !== got.length || !crypto.timingSafeEqual(good, got)) {
return { ok: false, reason: "bad_signature" };
}
const claims = JSON.parse(Buffer.from(body, "base64url"));
if (claims.iss !== ISSUER) return { ok: false, reason: "wrong_issuer" };
if (claims.aud !== audience) return { ok: false, reason: "wrong_audience" };
if (claims.exp <= now) return { ok: false, reason: "expired" };
return { ok: true, claims };
}
const now = 1_800_000_000;
const claims = { sub: "u_7", aud: "orders-api", exp: now + 600 };
const good = issueToken(claims);
const foreign = issueToken({ ...claims, iss: "evil.example" });
const cases = [
["valid", checkToken(good, { audience: "orders-api", now })],
["other audience", checkToken(good, { audience: "billing-api", now })],
["after expiry", checkToken(good, { audience: "orders-api", now: now + 601 })],
["foreign issuer", checkToken(foreign, { audience: "orders-api", now })],
["cut signature", checkToken(good.slice(0, -4), { audience: "orders-api", now })],
["two-part string", checkToken("abc.def", { audience: "orders-api", now })],
];
for (const [label, result] of cases) {
console.log(label.padEnd(16), result.ok ? "ok" : result.reason);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A bearer token travels as Authorization: Bearer <token>; anyone holding it can use it, so HTTPS and short lifetimes are essential.
- A JWT is header.payload.signature in base64url: signed but not encrypted, so anyone can read the payload.
- Before trusting a claim, pin the algorithm, verify the signature in constant time, and check exp (plus iss and aud).
- exp counts seconds while Date.now() counts milliseconds, and failures answer 401 with WWW-Authenticate.