Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 43 ยท Security and Auth

JWT Authentication and Authorization

Use JSON Web Tokens in Express: access and refresh tokens, the Bearer header, jsonwebtoken, role-based guards and the pitfalls of storing tokens in the browser.

Sessions keep the user's state on the server. A JSON Web Token (JWT) turns that around: the server signs a small piece of data (who the user is, what role they have, when the token expires) and hands it to the client. On later requests the client sends the token back, and the server only has to check the signature. No session lookup is needed, which is handy for APIs used by mobile apps, single-page apps and several cooperating services.

This lesson explains what is inside a JWT, how access and refresh tokens work together, how to read the Authorization: Bearer header, how to write role-based guards, and where tokens should not be stored. The real library (jsonwebtoken) is read-only because npm is not available here; the runnable examples implement HS256 signing from scratch with node:crypto on the stand-in framework from Inside Express. That is for learning only: in real projects use a maintained library.

Anatomy of a JWT

Three parts, two dots

Header Names the algorithm, such as HS256.
Payload Claims like sub, role, exp.
Signature Proves nobody changed the first two parts.

Format: header.payload.signature, each Base64URL.

1 / 2

A token looks like xxxxx.yyyyy.zzzzz. The first two parts are just Base64URL-encoded JSON. Encoding is not encryption: anyone holding the token can read the payload. What the signature gives you is integrity: only someone with the secret key could have produced a valid token, and any modification invalidates it.

Common claims (payload fields) are standardized: sub (subject, usually the user id), iat (issued at), exp (expiry, in seconds since 1970), iss (issuer) and aud (audience). You can add your own, such as role.

Signing and verifying with jsonwebtoken

This is the real code, read-only:

JavaScript
import jwt from 'jsonwebtoken';

const token = jwt.sign(
  { sub: String(user.id), role: user.role },
  process.env.JWT_SECRET,
  { algorithm: 'HS256', expiresIn: '15m', issuer: 'my-api' },
);

try {
  const payload = jwt.verify(token, process.env.JWT_SECRET, {
    algorithms: ['HS256'], // always pin the algorithm
    issuer: 'my-api',
  });
} catch (err) {
  // TokenExpiredError, JsonWebTokenError, ...
}

Always pass algorithms to verify. Historically some libraries could be tricked by tokens claiming the algorithm none (no signature) or by switching between asymmetric and symmetric algorithms. Pinning the accepted algorithm closes that door.

HS256 uses one shared secret for signing and verifying, which suits a single service. RS256/ES256 use a private key to sign and a public key to verify, which suits cases where many services must verify tokens but only one may issue them.

A runnable HS256 implementation

This stand-in shows what signing really is: an HMAC over header.payload. A fixed clock (nowSeconds) keeps the output the same on every run.

Node.js Signing and verifying a token by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You can see the payload is plain JSON, the forged role is caught because the signature no longer matches, and the same token is rejected once its exp has passed. Note the length check before timingSafeEqual: that function throws on buffers of different sizes, and it compares in constant time so timing does not leak how many characters matched.

Access and refresh tokens

A stolen JWT is valid until it expires, and you cannot easily "log out" a token the server does not store. The standard compromise uses two tokens:

  • Access token: short-lived (5 to 15 minutes), sent with every API request. If it leaks, the damage window is small.
  • Refresh token: long-lived (days or weeks), used only to obtain a new access token. It is stored server-side (or at least tracked), so it can be revoked, and ideally rotated: each use returns a new refresh token and invalidates the old one.
sequenceDiagram
  participant C as Client
  participant A as API
  C->>A: POST /login
  A-->>C: access (15 min) + refresh (7 days)
  C->>A: GET /notes<br/>Authorization: Bearer access
  A-->>C: 200
  Note over C,A: access token expires
  C->>A: GET /notes (expired access)
  A-->>C: 401
  C->>A: POST /refresh (refresh token)
  A-->>C: new access + new refresh

The refresh token is only used on the refresh endpoint, so it is exposed far less often.

The Bearer header and role guards

Clients send the access token in the Authorization header with the scheme Bearer:

HTTP
GET /notes HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

A middleware extracts it, verifies it, and attaches the result to the request. A second layer of middleware, a guard, then decides whether that user may do the thing. The words matter: authentication is "who are you?" (a missing or bad token gives 401), and authorization is "may you do this?" (a valid user without permission gives 403). Middleware factories like this are covered in Writing Your Own Middleware.

JavaScript
function authenticate(req, res, next) {
  const header = req.get('authorization') ?? '';
  const [scheme, token] = header.split(' ');
  if (scheme !== 'Bearer' || !token) {
    return res.status(401).json({ error: 'Missing bearer token' });
  }
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
}

const requireRole = (...roles) => (req, res, next) =>
  roles.includes(req.user.role) ? next() : res.status(403).json({ error: 'Forbidden' });

app.get('/notes', authenticate, listNotes);
app.delete('/users/:id', authenticate, requireRole('admin'), deleteUser);

Runnable: login, refresh and an admin route

This API uses the HS256 code from above. It issues a 60-second access token and a random refresh token kept in a server-side Map, so it can be rotated and revoked. The fake clock lets the example jump forward in time.

Node.js Access token, refresh token and roles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Follow the status codes: no token gives 401, Bob's valid token on an admin route gives 403 (authenticated but not allowed), Ada succeeds, then after the clock jump her access token is rejected as expired and the refresh endpoint issues a new pair. Reusing the old refresh token afterwards fails because rotation deleted it. In real systems a detected reuse is often treated as theft and the user's whole refresh family is revoked.

Where to store tokens in the browser

For browser apps this is the hardest question, and both options have a cost:

Storage Risk Notes
localStorage / sessionStorage Any XSS bug lets a script read the token. Not sent automatically, so no CSRF.
HttpOnly cookie Not readable by scripts, but sent automatically, so CSRF applies. Pair with SameSite and CSRF checks.
In memory (a JavaScript variable) Lost on reload; XSS can still use it while the page runs. Often paired with a refresh cookie.

A widely used pattern keeps the access token in memory and the refresh token in an HttpOnly, Secure, SameSite cookie limited to the refresh path. Mobile and server-to-server clients can use secure platform storage instead. See Cookies and Headers for cookie options.

Pitfalls to avoid

  • Weak secrets. An HS256 secret should be long and random (32 bytes or more), loaded from the environment.
  • Long-lived access tokens. You cannot revoke them, so keep them short.
  • Secrets in the payload. It is readable by everyone.
  • Trusting the payload without verifying. Decoding is not verifying.
  • Role data going stale. A role claim is valid until exp, even if you demote the user meanwhile; keep lifetimes short or check the database for sensitive actions.
  • Choosing JWT by default. For a classic website with one server, plain sessions are simpler and easier to revoke.

The wider checklist, including rate limiting login endpoints, is in Security Best Practices.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the signature of a JWT protect?

    Signing gives integrity, not secrecy. The payload is only Base64URL-encoded and readable by anyone.
  2. 2. A user sends a valid token but their role is "user" and the route needs "admin". Which status fits best?

    403 means the user is authenticated but not allowed. 401 is for a missing or invalid token.
  3. 3. Why are access tokens kept short-lived?

    Since the server does not track access tokens, expiry is the main limit on damage after a leak.
  4. 4. What is refresh-token rotation?

    One-time refresh tokens make theft detectable: if an old token appears again, something is wrong.
  5. 5. Which option should you pass to jwt.verify to avoid algorithm-confusion attacks?

    Pinning the accepted algorithms means a token claiming "none" or a different algorithm is rejected.

Summary

  • A JWT is header.payload.signature: readable by anyone, tamper-proof thanks to the signature.
  • Use short-lived access tokens with the Authorization: Bearer header and longer-lived, revocable, rotated refresh tokens.
  • Authentication (401) says who you are; authorization (403) decides what you may do, often with a requireRole guard.
  • Always pin algorithms, use strong secrets and keep sensitive data out of the payload.
  • Token storage in browsers is a trade-off between XSS (localStorage) and CSRF (cookies); in-memory access tokens plus an HttpOnly refresh cookie are a common compromise.

Next: Security Best Practices.