Skip to content

15 min read

What is JWT? Session vs JWT authentication

In one sentence: A JWT is a token that carries who you are and until when it's valid, with a signature so nobody can change it. Anyone can read it, and it can't be canceled before it expires: that's why, for people in a browser, a session is better. JWTs fit between services, and a program identifies itself with an API key.

What you will learn

  • Read a JWT piece by piece (header, payload and signature) and explain why it's signed, but not encrypted.
  • Check a JWT properly, with the signature, the algorithm, the expiry and the audience, and recognize the typical mistakes.
  • Choose between a session and a JWT, and explain why a JWT isn't a better session.
  • Give a program its own API key, stored as a hash and sent in Authorization Bearer.

Before you start, read: 02-sessions.md

The delivery company from Phase 4, Fast Delivery, wants its program to mark orders as shipped. But a program has no browser and doesn’t type passwords into a form. How does it tell the shop who it is? Today, the only way would be to give it the ADMIN_TOKEN, and in the introduction you saw what that means.

While you think about it, Luis reads on a forum: “Sessions in the database are outdated. Use JWT: the server doesn’t store anything.” Is he right?

This lesson answers both.

The analogy

At a theater’s coat check they give you a ticket with a number, 47. The ticket says nothing: the coat, and whose it is, are in the coat check. If you lose it and tell them, they cancel it on the spot. That’s the session from lesson 2.

At a festival they put a wristband on you that says it all, “VIP Area · Saturday,” with a hologram only the organizers make. Every bar checks it by looking at it, without calling anyone. But anyone who sees it reads what it says, and if it’s stolen, it works until Sunday: no bar finds out. That’s a JWT.

Where the analogy breaks down

  • A hologram can be imitated with patience. A JWT’s signature can’t be made without the secret, if it’s long and random.
  • A wristband can be read at a glance. A JWT looks like gibberish, but it isn’t encrypted: one command reads it.
  • The wristband is tied to your wrist. A JWT isn’t: whoever copies it gets in.

This is a JWT made by this lesson’s example, examples/jwt.ts:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiY3VzdG9tZXIiLCJzdWIiOiJjYXJtZW4iLCJpc3MiOiJzaG9wLWFwaSIsImF1ZCI6InNob3AtYXBpIiwiaWF0IjoxNzkxOTUyOTI0LCJleHAiOjE3OTE5NTM4MjR9.YquKMDhnqilUifK7j_2mf9FUwANwm8OwJjsSAR68VNE

It has three parts, separated by dots:

Part What it carries In this token
Header How it’s signed {"alg":"HS256","typ":"JWT"}
Payload What the token claims {"role":"customer", "sub":"carmen", "iss":"shop-api", "aud":"shop-api", "iat":1791952924, "exp":1791953824}
Signature 32 bytes that prove nobody has changed the other two It can’t be read: it’s bytes

A JWTJWT stands for JSON Web Token.A piece of text with some data in JSON, like who someone is and until when it’s valid, and a signature that proves who issued it and that nobody has changed it. It usually isn’t encrypted, so anyone who has it can read it, and it can’t be canceled before it expires without keeping a separate list.Go to definition (JSON Web Token, pronounced like the word jot) is just that: signed JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition that fits in a header. The names in the payload are short because they travel in every request, and RFC 7519 defines them:

  • sub (subject): who the token is about.
  • iss (issuer): who issued it.
  • aud (audience): who it’s for, which server should accept it.
  • iat and exp (issued at, expiration): when it was made and when it expires, in seconds since January 1, 1970. 1791952924 is October 14, 2026, at 04:42:04 UTC, and exp, fifteen minutes later.

role isn’t standard: whoever issues the token adds whatever data they want.

The first two parts are in base64url. Base64 writes any data with 64 printable characters: letters, digits, + and /. The url variant swaps those two for - and _, which fit in a URL, and drops the = at the end. That’s why every JWT starts with eyJ: it’s {" in base64.

There’s no key at all: any program undoes it. A JWT is signed, not EncryptionTransforming a message with a key so that only someone with the key to decrypt it can read it. If the same key encrypts and decrypts, it is symmetric; if there are two different keys, a public one and a private one, it is asymmetric.Go to definition: whoever has it reads everything it carries. There’s an encrypted variant, JWE, but the JWTs you’ll see are like this one. Never put anything in one that the person carrying it can’t see.

The signature hides nothing. It guarantees two things: that it was issued by whoever has the key, and that nobody has changed a single letter.

Signing and checking: a secret or a key pair

Section titled “Signing and checking: a secret or a key pair”

The header says in alg how it was signed. There are two families:

  • HS256: an HMACHMAC stands for Hash-based Message Authentication Code.A signature computed with a hash from a message and a secret that both parties know. Whoever has the secret can check that the message comes from the other party and that nobody has changed it; whoever doesn’t have it can’t forge one.Go to definition-SHA256 of the first two parts with a SecretA piece of data that gives access to something and that only the people and programs that need it should know, like a database password or an API key. It’s never written inside the code.Go to definition, like the signature of the webhooks in Phase 4. The same secret signs and checks: whoever can check can forge.
  • RS256 or ES256: a Digital signatureA few bytes someone computes from a message with their private key. With the public key, anyone can check that the message hasn’t changed and that the owner of that key signed it.Go to definition with a Private keyThe half of a key pair that only its owner knows. It decrypts what was encrypted with its public key and signs messages anyone can check with the public key. If it leaks, it must be replaced.Go to definition, which anyone checks with the Public keyThe half of a key pair you can show to anyone. It is used to encrypt messages that only the private key will decrypt, and to check the signatures the private key makes.Go to definition one, as in TLS. Only the issuer signs. That’s how Google signs the tokens for “Sign in with Google,” and it publishes its public keys so any website can check them (lesson 4, “OAuth”).

The example uses HS256 with jose, the most widely used JWT library in Node, with no dependencies:

examples/jwt.ts
// The token says who it is (sub), who issues it (iss), who it's for (aud) and until when it's
// valid (exp). expires: a text like '15m' or the seconds since 1970.
export function createToken(sub: string, aud = 'shop-api', expires: string | number = '15m') {
return new SignJWT({ role: 'customer' })
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setSubject(sub)
.setIssuer('shop-api')
.setAudience(aud)
.setIssuedAt()
.setExpirationTime(expires)
.sign(secret);
}
  • new SignJWT({ role: 'customer' }) starts the token with a piece of data of its own.
  • setProtectedHeader writes the header, and each set…, a standard field. '15m' is fifteen minutes.
  • .sign(secret) computes the signature. The secret comes from the Environment variableA name with a value, like PORT=3000, that a program receives when it starts from whoever starts it, for example the shell. It lets you configure the program without changing its code and give it secrets without writing them in it.Go to definition JWT_SECRET or, if it doesn’t exist, it’s 32 random bytes, different on every run.

Checking is more than reading:

examples/jwt.ts
// Checking is more than reading: the signature (did whoever has the secret sign it?, has anything
// changed?), the algorithm (only HS256: never the one the token itself says), the issuer, the
// audience and the expiry. If something fails, jose throws an error with a code that says what.
export async function check(token: string, aud = 'shop-api') {
try {
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256'],
issuer: 'shop-api',
audience: aud,
});
return { valid: true as const, payload };
} catch (error) {
return { valid: false as const, reason: (error as { code?: string }).code ?? String(error) };
}
}
  • jwtVerify recomputes the signature with the secret and compares it. If it matches, it looks at exp, iss and aud.
  • algorithms: ['HS256']: the algorithm is decided by whoever checks, never by the token. You’ll see why in a moment.
  • If something fails, jose throws an error with a code that says what, like ERR_JWT_EXPIRED.

RFC 8725 collects the mistakes seen in real life. The ones that matter most:

  • alg: none. The standard allows unsigned tokens, with "alg":"none". A library that obeys the header accepts one forged by anyone, with an empty signature. In 2015, several accepted it. The defense: the algorithms list.
  • Reading without checking. Libraries come with a function to read the payload without looking at the signature (in jose, decodeJwt). Deciding with it means believing whatever the sender of the token says.
  • Not looking at exp or aud. Without an expiry, a stolen token works forever. Without an audience, a token the shop made for the payment gateway would also work at the shop. jose looks at exp if the token has it, but at aud and iss only if you ask it to.
  • A short secret. With a token in hand, secrets are tried on another computer, millions per second, as with the passwords in lesson 1. jose accepts a three-letter one without complaining. Use 32 random bytes.
  • Storing it where JavaScript can read it. Many websites keep it in localStorage. If someone runs their JavaScript on the page (the XSSXSS stands for Cross-Site Scripting.An attack in which a web page includes text someone else wrote, and that text carries JavaScript code that each visitor’s browser runs as if it were the page’s own. It’s prevented by replacing the special characters in each piece of data, like “<”, with a version the browser shows but never reads as code.Go to definition from lesson 6), they take it. An HttpOnly cookie can’t be read from JavaScript.

And the biggest one, which isn’t a code mistake: it can’t be canceled.

The argument Luis read on the forum is half true: with JWT, the server doesn’t store anything. Look at what it costs:

Session (lesson 2) JWT
What the client carries A random 43-character id that says nothing The signed data: 217 characters in the example, in every request
What the server stores One row per session Nothing, only the secret or the key to check it
How it’s checked A query by Primary keyThe column, or group of columns, that identifies each row of a table. Its value can’t repeat or be missing, like an order number.Go to definition A calculation, with no database
Signing out or canceling it The row is deleted: it doesn’t work on the next request Impossible: it works until exp
If you take a permission away from someone On the next request When their token expires

To cancel a JWT early, the server has to note down the canceled ones and look them up on every request: a table and a query, what the JWT promised to save. The usual fix, a fifteen-minute JWT plus a second token to renew it stored in the database, turns back into a session with more pieces.

And the savings are small: the shop already talks to PostgreSQL on almost every request, and looking up by primary key is one of the fastest things it does (indexes lesson).

The course’s answer: sessions for people in a browser; JWT between services. A JWT fits when one server has to trust another without asking it. For example, the shop could give the payment gateway a one-minute token with aud: payment-gateway. And an identity provider tells you who you are with a JWT, the OpenID Connect id_token from lesson 4.

And Fast Delivery? Its program runs on a server, day and night, with nobody in front of it. A JWT that never expires would be a key that’s impossible to take back. It needs an API keyAPI stands for Application Programming Interface.A long, random piece of text that identifies a program, not a person, when it calls an API. It travels with every request, usually in the Authorization header. A good server keeps only its hash, and to take away its access, deleting it is enough.Go to definition: a long, random piece of text that identifies it, like a session that doesn’t expire and is canceled by deleting it. This is how it’s created, in src/api-keys.ts:

src/api-keys.ts
// They all start with shop_: whoever finds one in a log or in a repository knows where it's from
// (and GitHub can recognize them and warn, as it does with other companies' keys). After it, 32
// random bytes.
export const KEY_PREFIX = 'shop_';
// Returns the key only once: the table only keeps its hash. If it's lost, another one is created.
export async function createKey(name: string): Promise<{ id: number; key: string }> {
const key = KEY_PREFIX + randomBytes(32).toString('base64url');
const [row] = await db
.insert(apiKeys)
.values({ name, hash: hashOfKey(key) })
.returning({ id: apiKeys.id });
return { id: row!.id, key };
}
// SHA-256, like the sessions' id: the key is random and long, a slow hash isn't needed.
const hashOfKey = (key: string) => createHash('sha256').update(key).digest();
  • randomBytes(32): 256 random bits, like the session id. Nobody guesses it.
  • shop_ in front: whoever finds it in a log or in a repository knows where it’s from. That’s how GitHub recognizes other companies’ keys and warns if they’re pushed: ghp_ ones are GitHub’s, and sk_live_ ones, Stripe’s.
  • The table stores its HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition, never the key: the key is shown once, when it’s created. SHA-256, a fast one, is enough: argon2 slows down whoever tries likely passwords (lesson 1), and for a random key there’s no list to try.

On every request a new MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition looks it up, src/middleware/api-key.ts:

src/middleware/api-key.ts
// Like loadSession, but for programs: if the request brings a key that exists, it leaves it in
// c.var.apiKey. The prefix tells it apart from a session id, which can also arrive as Bearer.
export const loadApiKey: MiddlewareHandler<Env> = async (c, next) => {
const token = /^Bearer (\S+)$/.exec(c.req.header('Authorization') ?? '')?.[1];
if (token?.startsWith(KEY_PREFIX)) {
const apiKey = await findKey(token);
if (apiKey) c.set('apiKey', apiKey);
}
await next();
};
  • It reads Authorization: Bearer …, the header from Phase 2. The prefix tells it apart from a session id, which can also arrive that way.
  • findKey looks it up by its hash and notes in used_at when it was used: a forgotten key can be deleted.

With no session and no key, requireIdentity answers 401 with WWW-Authenticate: Bearer realm="shop-api", the challenge RFC 6750 describes. For now, the key only identifies: GET /v2/me says who you are. What Fast Delivery can do with it comes in lesson 5, “Authorization”.

The goal: make a JWT, read it without the secret and watch four tricks get rejected. Then, give Fast Delivery its key and check that a fake one doesn’t get in and that the shop doesn’t store the real one.

You’ll break your own tokens, on your own computer: doing it against someone else’s system without permission is a crime.

You start from your project from lesson 2, “Sessions”.

1. Install jose

Ventana de terminal
npm install jose@6.2.12

What you will see:

added 1 package, and audited 71 packages in 2s
9 packages are looking for funding
run `npm fund` for details
4 moderate severity vulnerabilities
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.

A single package: jose depends on nobody. The 4 vulnerabilities are drizzle-kit’s, from Phase 5’s “ORM” lesson. This lesson’s outputs are from Node 26.11.1 and PostgreSQL 18.6.

Add the table to src/schema.ts:

src/schema.ts
export const apiKeys = pgTable('api_keys', {
id: integer().primaryKey().generatedAlwaysAsIdentity(),
name: text().notNull(),
hash: bytea().notNull().unique(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
usedAt: timestamp('used_at', { withTimezone: true }),
});

unique() prevents two equal hashes and creates the index used to look up each key.

2. Generate the migration

Ventana de terminal
npm run db:generate -- --name=api-keys

What you will see:

> shop-api@1.0.0 db:generate
> drizzle-kit generate --name=api-keys
No config path provided, using default 'drizzle.config.ts'
Reading config file '/Users/ana/backend-course/phase-3/shop-api/drizzle.config.ts'
9 tables
api_keys 5 columns 0 indexes 0 fks
categories 2 columns 0 indexes 0 fks
idempotency_keys 6 columns 0 indexes 0 fks
orders 5 columns 1 indexes 1 fks
processed_events 2 columns 0 indexes 0 fks
product_categories 2 columns 1 indexes 2 fks
products 4 columns 0 indexes 0 fks
sessions 4 columns 0 indexes 1 fks
users 4 columns 1 indexes 0 fks
[✓] Your SQL migration file ➜ drizzle/0004_api-keys.sql 🚀

As in lessons 1 and 2: drizzle/0004_api-keys.sql has the CREATE TABLE. If you get No schema changes, you didn’t save schema.ts.

With that SQL, and with comments that explain it, write db/migrations/007-api-keys.sql:

db/migrations/007-api-keys.sql
CREATE TABLE api_keys (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
-- Whose it is, so a person can recognize it: "Fast Delivery".
name text NOT NULL,
-- The key's SHA-256. UNIQUE: besides preventing two equal ones, it creates the index used to
-- find the key that arrives in each request.
hash bytea NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
-- The last time it was used: a key nobody has used for months can be deleted.
used_at timestamptz
);

3. Apply it

Ventana de terminal
npm run db:migrate

What you will see:

> shop-api@1.0.0 db:migrate
> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 007-api-keys.sql

Only the new one: the other six were already there.

Then:

  1. Create src/api-keys.ts and src/middleware/api-key.ts.
  2. In src/env.ts, add apiKey?: ApiKey. In src/app.ts, app.use(loadApiKey) right after app.use(loadSession).
  3. Change requireIdentity (src/middleware/session.ts), so that a key also counts; meSchema (src/schemas.ts), getMe (src/contract.ts) and the /me route (src/v2.ts), which now say whether you’re a person or a key. Whatever you haven’t seen here, copy it from the step.
  4. Add the create-key script to package.json (the highlighted line):
package.json
{
"name": "shop-api",
"version": "1.0.0",
"private": true,
"type": "module",
"engines": {
"node": ">=24"
},
"scripts": {
"start": "node --env-file-if-exists=.env src/server.ts",
"dev": "node --env-file-if-exists=.env --watch src/server.ts",
"test": "node --env-file=test/.env --test --test-concurrency=1",
"check": "tsc --noEmit",
"gateway": "node --env-file-if-exists=.env scripts/payment-gateway.ts",
"db:migrate": "node --env-file-if-exists=.env scripts/migrate.ts",
"db:seed": "node --env-file-if-exists=.env scripts/seed.ts",
"db:many-orders": "node --env-file-if-exists=.env scripts/many-orders.ts",
"db:generate": "drizzle-kit generate",
"create-key": "node --env-file-if-exists=.env scripts/create-key.ts"
},
"dependencies": {
"@hono/node-server": "2.1.8",
"@hono/zod-openapi": "1.6.3",
"@hono/zod-validator": "0.9.1",
"@scalar/hono-api-reference": "0.12.10",
"drizzle-orm": "0.45.3",
"hono": "4.13.18",
"jose": "6.2.12",
"pg": "8.23.1",
"pino": "10.4.0",
"protobufjs": "8.8.0",
"ws": "8.22.0",
"zod": "4.6.7"
},
"devDependencies": {
"@types/node": "26.6.4",
"@types/pg": "8.23.1",
"@types/ws": "8.18.2",
"drizzle-kit": "0.31.11",
"typescript": "7.0.2"
}
}

The example, the script and the tests come in this lesson’s folder:

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/26-jwt-keys.tar.gz
tar -xzf 26-jwt-keys.tar.gz
cd shop-api
cp ../26-jwt-keys/examples/jwt.ts examples/
cp ../26-jwt-keys/scripts/create-key.ts scripts/
cp ../26-jwt-keys/test/*.ts test/

If you get stuck, compare with 26-jwt-keys. npm test should end with fail 0.

4. The example, from start to finish

Ventana de terminal
node examples/jwt.ts

What you will see:

The token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiY3VzdG9tZXIiLCJzdWIiOiJjYXJtZW4iLCJpc3MiOiJzaG9wLWFwaSIsImF1ZCI6InNob3AtYXBpIiwiaWF0IjoxNzkxOTUyOTI0LCJleHAiOjE3OTE5NTM4MjR9.YquKMDhnqilUifK7j_2mf9FUwANwm8OwJjsSAR68VNE
Header: { alg: 'HS256', typ: 'JWT' }
Payload: {
role: 'customer',
sub: 'carmen',
iss: 'shop-api',
aud: 'shop-api',
iat: 1791952924,
exp: 1791953824
}
Signature: 32 bytes
As is: valid
With the payload changed: rejected (ERR_JWS_SIGNATURE_VERIFICATION_FAILED)
With alg: none and no signature: rejected (ERR_JOSE_ALG_NOT_ALLOWED)
Expired a minute ago: rejected (ERR_JWT_EXPIRED)
For another audience: rejected (ERR_JWT_CLAIM_VALIDATION_FAILED)

It needs neither PostgreSQL nor the server. Your token and your times will be different. Look at the four tricks:

  • Payload changed: sub goes from carmen to pablo with the old signature, which no longer matches.
  • alg: none: none isn’t in algorithms.
  • Expired: a good signature, but exp has already passed.
  • Another audience: a good signature, but it’s for payment-gateway.

If you get Cannot find package 'jose', step 1 is missing.

Now read it without the secret and without jose, as anyone who copies it would:

5. Read it with base64

Ventana de terminal
TOKEN=$(node examples/jwt.ts | sed -n 2p)
echo "$TOKEN" | cut -d. -f1 | base64 -d
echo
echo "$TOKEN" | cut -d. -f2 | base64 -d
echo

What you will see:

{"alg":"HS256","typ":"JWT"}
{"role":"customer","sub":"carmen","iss":"shop-api","aud":"shop-api","iat":1791952952,"exp":1791953852}

sed -n 2p keeps the second line, the token, and cut -d. -f1, the first part between dots (pipes lesson in Phase 1). base64 -d decodes it. Each lone echo adds a line break.

And the = that base64 usually ends with? base64url drops that padding, and this token’s header and payload need none: each is a multiple of four characters long. Other data may need one or two, and without them macOS’s base64 eats the last characters, like the closing }: add them at the end. On Linux it comes out right with or without them.

Challenge: HS256 is the HMAC from Phase 4. Compute a token’s signature yourself with openssl and compare it with its third part.Show answer

Set the secret yourself and sign the first two parts, with the dot in between:

Ventana de terminal
export JWT_SECRET=the-shop-secret
TOKEN=$(node examples/jwt.ts | sed -n 2p)
echo "$TOKEN" | cut -d. -f3
printf '%s' "$(echo "$TOKEN" | cut -d. -f1-2)" | openssl dgst -sha256 -hmac "$JWT_SECRET" -binary | base64 | tr '+/' '-_' | tr -d '='
LgFyGQ2jelblGQP0CIN0RfxLhGrtphV39MC3owfsiGA
LgFyGQ2jelblGQP0CIN0RfxLhGrtphV39MC3owfsiGA

The two lines are the same. -binary gives the HMAC’s 32 bytes, and tr turns them from base64 into base64url. With the secret, anyone can sign whatever they want: that’s why it lives in the .env, and it’s never a password.

Start the server with npm start and open another terminal in the project folder.

6. Create the key

Ventana de terminal
npm run create-key -- "Fast Delivery"

What you will see:

> shop-api@1.0.0 create-key
> node --env-file-if-exists=.env scripts/create-key.ts Fast Delivery
Key 1, for "Fast Delivery":
shop_1xwE7_-ZdFKf-QppIUiXPDm5nE-MunX4K2X9YCfG9dI
Copy it now: the shop only keeps its hash and cannot show it to you again.

Whatever goes after -- reaches the script, and the quotes make Fast Delivery a single name. Your key will be different: copy it.

7. Who am I, with the key

Ventana de terminal
KEY=shop_1xwE7_-ZdFKf-QppIUiXPDm5nE-MunX4K2X9YCfG9dI
curl -s -w '\n' -H "Authorization: Bearer $KEY" localhost:3000/v2/me

What you will see:

{"type":"key","id":1,"name":"Fast Delivery"}

Put your key after KEY=. The shop recognizes a program, not a person: type is key. If you get a 401, the variable is empty or a character is missing.

8. With a fake key

Ventana de terminal
curl -s -i -H 'Authorization: Bearer shop_1xwE7_-ZdFKf-QppIUiXPDm5nE-MunX4K2X9YCfG9dx' localhost:3000/v2/me

What you will see:

HTTP/1.1 401 Unauthorized
content-type: application/problem+json
vary: Origin
www-authenticate: Bearer realm="shop-api"
x-request-id: f3e7592e-3e90-4435-8acb-8ec101bd7e2a
content-length: 117
Date: Wed, 14 Oct 2026 04:42:57 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"type":"about:blank","title":"Unauthorized","status":401,"detail":"Sign in, or identify yourself with your API key"}

The same key with the last character changed: 401, and www-authenticate says how to identify yourself. The shop doesn’t tell you whether it looks like a good one: only “I don’t know who you are.”

9. What the shop stores

Ventana de terminal
psql -d shop -c "SELECT id, name, encode(hash, 'hex') AS hash, used_at FROM api_keys;"
printf '%s' "$KEY" | shasum -a 256

What you will see:

id | name | hash | used_at
----+---------------+------------------------------------------------------------------+-------------------------------
1 | Fast Delivery | 9b7478d1728da9a63c216c314105174ef65944501ba04da4f6721042e6f042d5 | 2026-10-14 04:42:50.813141+00
(1 row)
9b7478d1728da9a63c216c314105174ef65944501ba04da4f6721042e6f042d5 -

encode(hash, 'hex') writes the bytes in hexadecimal: your key’s SHA-256, the same one shasum computes. The key isn’t anywhere, and whoever copies the table can’t use it. used_at is the time of step 7.

To cancel the key, deleting its row is enough: the next request gets a 401. That’s what a JWT can’t do.

  • “Sign in with Google.” The website receives from Google a JWT signed with its private key: the id_token from lesson 4.
  • A header that starts with eyJ. In the Network tab of DevTools, many websites send Authorization: Bearer eyJ…: a JWT, which you read with base64 as here. Don’t paste it into a website that “decodes tokens”: a real token isn’t shown to anyone.
  • The keys of the services you use. A maps or payments service gives you a key, and shows it to you only once.
  • Putting in the JWT what nobody should read. It’s in base64url, not encrypted.
  • Letting the token choose the algorithm, or reading it without checking it. Set algorithms and use jwtVerify, never decodeJwt, to decide.
  • Using JWTs that last days as a session. They can’t be canceled. For people in a browser, a session.
  • A short secret, or the same one for two things. 32 random bytes, one per use: don’t reuse the WEBHOOK_SECRET.
  • The API key in the URL or in the frontend. URLs end up in logs, and anyone can read a page’s JavaScript. It goes in Authorization, from a server.
  • Storing the key as is. Store its hash, and show it only once.
  • A JWT is three parts in base64url: header, payload and signature. It’s signed, not encrypted: anyone can read it.
  • HS256 signs with a shared secret, an HMAC; RS256 and ES256, with a private key that’s checked with the public one.
  • Checking means looking at the signature with a fixed algorithm, exp, iss and aud. alg: none and reading without checking are the classic mistakes.
  • A JWT can’t be canceled before exp. Sessions for people in a browser; JWT between services and as an id_token.
  • A program identifies itself with an API key: long, random, stored as a hash, sent in Authorization: Bearer and canceled by deleting it.
A coworker puts the customer’s address and phone number in the payload of their app’s JWT: “it’s signed, so it’s protected.” What do you tell them?

Someone sends an API a token with alg: none in the header, sub: pablo in the payload and an empty signature, and the API lets them in as Pablo. Where is the flaw?

The shop gives its customers a JWT that lasts a week. Carmen’s laptop is stolen with her session open. What can the shop do today?

In DevTools you see Authorization: Bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI0MiJ9.k3Hq… What can you learn without any key?

The shop stores passwords with argon2 and API keys with SHA-256. Why not argon2 for the keys too?

Fast Delivery suggests sending its key in the URL, /v2/orders?key=shop_…, because it’s easier to program. What do you answer?

phase-6 · lesson 3/9