Backend engineering concepts · Part 2 of 2
  1. Authentication Explained: Sessions vs JWT
  2. Authentication Explained: Access Tokens and Refresh Tokens

Authentication Explained: Access Tokens and Refresh Tokens

On this page
  1. One Token Can't Be Short and Long at Once
  2. Two Tokens, Two Jobs
  3. What Alice sees: nothing
  4. The code that does it
  5. The Refresh Token Is a Session in Disguise
  6. A Refresh Token Should Only Work Once
  7. Where to Keep Each Token
  8. You May Not Need Refresh Tokens
  9. So Far, the Shop Makes Its Own Tokens
  10. Further Reading

32 logins a day.

That's what a 15-minute login costs someone working an 8-hour day. So why do the apps on your phone almost never ask you to log in again?

They don't use one long login. They use two tokens.

Show a short-lived token on every request. Keep a long-lived one that's only used to get a new short one.

This is Part 2 of a three-part series on authentication. Part 1 showed how sessions and JWTs remember you. This part shows how to keep logins short without logging people out all day, and where to keep the tokens in the browser.

One Token Can't Be Short and Long at Once#

Part 1 ended with a choice. After Alice logs in to the shop, she gets a session ID or a JWT, and it has an end time. Someone has to pick that end time.

Pick 15 minutes, and a stolen login stops working quickly. But Alice has to type her password again every 15 minutes she's using the shop. Over an 8-hour day, that's up to 32 logins. Nobody will put up with that.

Pick 30 days, and Alice stays logged in. But a copied login also works for 30 days. With a JWT, Part 1 showed that logging out doesn't even stop it, because there's nothing on the server to delete.

So the time we pick is either annoying or dangerous. That's because we're asking one token to do two jobs:

  • Prove who Alice is on every request. This token gets sent all the time, so it should die quickly.
  • Keep Alice logged in for weeks. This one needs to last, so it should be sent as rarely as possible, and the server should be able to cancel it.

Those two needs pull in opposite directions. So we stop asking one token to do both.

Two Tokens, Two Jobs#

After login, the server now gives Alice two tokens instead of one:

Access token Refresh token
Its job Proves who Alice is on every request Gets a new access token, nothing else
Lives for Minutes (15 in our example) Days or weeks (30 in our example)
Sent to Every API call Only POST /auth/refresh
Usually A JWT, checked by its signature A long random string, looked up on the server

The idea comes from OAuth 2.0, the standard behind "Sign in with Google". Its spec, RFC 6749, describes refresh tokens as tokens "used to obtain access tokens". That's their only job.

Think of a gym:

  • The day wristband (access token). Staff glance at it at every door: the weights room, the pool, the lockers. Nobody looks you up. It only works for today.
  • Your membership at reception (refresh token). You only show it at the front desk, to get a new wristband. Reception checks its records every time, and it can cancel your membership.

You show the wristband all day. You show the membership once.

What Alice sees: nothing#

Here's Alice's afternoon. She logs in at 5:00 pm, and her access token lasts 15 minutes:

5:00 pm  POST /login              → 200  access A1 (until 5:15) + refresh R1
5:10 pm  GET  /orders + A1        → 200  A1 is still valid
5:16 pm  GET  /orders + A1        → 401  A1 has expired
5:16 pm  POST /auth/refresh + R1  → 200  new access A2 (until 5:31)
5:16 pm  GET  /orders + A2        → 200  Alice never noticed

At 5:16 her request fails. But Alice doesn't see an error. The browser code catches the 401, swaps the refresh token for a new access token, and sends the request again. To Alice, the page just loads.

She only has to type her password again when the refresh token itself has expired or been cancelled.

Alice is about to log in at 5:00 pm. Press Play, or step through it.

The access token is the day wristband. The refresh token is the membership at reception.

The code that does it#

This is all the browser needs. It keeps the access token in a variable, and it refreshes once when a request comes back 401:

JavaScript
let accessToken = null; // kept in memory, not in localStorage
let refreshing = null;  // one refresh at a time

function refresh() {
  // The refresh token is in an HttpOnly cookie, so the browser sends it for us.
  refreshing ??= fetch("/auth/refresh", { method: "POST" })
    .then(async (res) => {
      if (!res.ok) throw new Error("Please log in again");
      accessToken = (await res.json()).accessToken;
    })
    .finally(() => (refreshing = null));
  return refreshing;
}

export async function api(url, options = {}) {
  const send = () =>
    fetch(url, {
      ...options,
      headers: { ...options.headers, Authorization: `Bearer ${accessToken}` },
    });

  let res = await send();
  if (res.status === 401) {
    await refresh();    // get a new access token
    res = await send(); // and try once more
  }
  return res;
}

The refreshing variable matters more than it looks. If the page sends five requests at 5:16, all five get a 401. Without it, all five would call refresh at the same time. With it, they wait for one refresh and share the result. You'll see why that matters in the rotation section.

The Refresh Token Is a Session in Disguise#

Here's the part that makes this work. The server keeps a record of every refresh token it hands out: whose it is, which device, and when it expires.

That's a session, from Part 1, under another name.

So logout works again. When Alice logs out, the server deletes her refresh token record. "Log out of all devices" deletes all of her records. A copied refresh token stops working right away.

The access token still can't be cancelled. It's a JWT, so there's nothing on the server to delete. But it dies within 15 minutes, so the damage has a limit.

That's the trade:

  • On almost every request, the server only checks a signature. No lookup, just like a JWT.
  • Once every 15 minutes, the browser refreshes, and the server looks up a record, just like a session.

In Alice's 8-hour day, that's up to 32 refreshes she never sees, instead of 32 logins she does.

Try it. Start the clock, log Alice out, then let the attacker try both copied tokens:

attacker got in attacker blocked5:00 pm

At 5:00 pm Alice logs in, and someone copies both of her tokens. Start the clock, log Alice out, then let the attacker try.

Each simulated minute takes 0.4 seconds. The access token lasts until 5:15 (the dashed line). The refresh token lasts 30 days, unless Alice logs out. Compare with Part 1, where the copied JWT worked for the whole hour.

The 15 minutes are still real. If someone copies Alice's access token, logging out doesn't stop it until it expires. A shorter access token makes that window smaller. It never closes it.

A Refresh Token Should Only Work Once#

The refresh token lasts 30 days, and it can make new access tokens. That makes it the token an attacker really wants.

The fix is refresh token rotation. Every time Alice refreshes, the server gives her a new refresh token along with the new access token, and the old one stops working. R1 becomes R2, R2 becomes R3, and so on.

On its own, that doesn't stop a thief. The trick is what happens when an old token comes back:

  1. Someone copies Alice's refresh token, R1.
  2. At 5:16 Alice's browser refreshes with R1. The server marks R1 as used and gives her A2 and R2.
  3. At 6:00 the attacker sends R1.
  4. The server sees a token that was already used. Two people must have it, and the server can't tell which one is Alice.
  5. So it cancels the whole chain, R2 included. The attacker gets a 401.
  6. Alice's next refresh with R2 fails too, so she logs in again with her password. The attacker doesn't have that.

Alice logs in one extra time. The attacker is locked out. It works the other way round too: if the attacker refreshes first, Alice's R1 comes back later and the chain is cancelled the same way.

Back at the gym, it's like reception swapping your membership card for a new one at every visit and shredding the old one. If someone ever shows up with a shredded card, reception knows a copy exists and cancels the membership.

Someone has copied Alice’s refresh token, R1. Press Play, or step through it.

Each refresh token works once. When a used one comes back, the whole chain is cancelled.

The OAuth security guidance, RFC 9700, asks for exactly this for apps that run in the browser: rotate refresh tokens, or tie them to the device.

This is also why the code above shares one refresh. If five requests refreshed with R1 at the same moment, the second one would look like a stolen token, and Alice would be logged out. Two open tabs can still race each other like this, so many auth libraries keep accepting the old refresh token for a few seconds after it's replaced.

Where to Keep Each Token#

Part 1 said whoever holds a token is treated as Alice. So where the browser keeps it matters. There are two dangers to plan for:

  • A bad script on the page (XSS). If an attacker gets JavaScript to run on your site, through a bad npm package or a comment box that doesn't clean its input, that script can read anything JavaScript can read, and send it away.
  • Another website tricking the browser (CSRF). Cookies are sent automatically. So a different site can make Alice's browser send a request to your shop, with her cookie attached. The SameSite setting on a cookie stops most of this.

Here's how the three common places compare:

Where Can a bad script read it? Sent automatically? Use it for
localStorage Yes No Not for tokens
A JavaScript variable Not easily, and it's gone when the page closes No The access token
HttpOnly cookie No Yes The refresh token

OWASP is direct about the first row: "Do not store session identifiers in local storage as the data is always accessible by JavaScript."

So a common setup is:

  • The access token lives in memory, in a variable like the accessToken above. When Alice reloads the page it's gone, so the page calls refresh and gets a new one.
  • The refresh token lives in a cookie the page can't read, sent only to the refresh endpoint:
Set-Cookie: refresh_token=R1...; HttpOnly; Secure; SameSite=Strict; Path=/auth/refresh

HttpOnly hides it from JavaScript, Secure keeps it on HTTPS, SameSite=Strict stops other sites from sending it, and Path means the browser only attaches it to /auth/refresh, not to every request.

One honest line: no storage is safe if a bad script is already running on your page. It can still send requests as Alice while she has the page open. What HttpOnly stops is the token being stolen and used later, from somewhere else. That's still a big difference.

You May Not Need Refresh Tokens#

None of this means every app needs two tokens.

If your app uses plain sessions, the default from Part 1, you already have instant logout. To keep Alice logged in while she's active, renew her session as she uses the app. It's easy to get that renewal wrong, as I found when a session logged users out while they were still active, but it's one token and one record.

Refresh tokens earn their place when the access token is a JWT:

  • several services need to check who Alice is without sharing a session store,
  • a mobile app needs to stay logged in for weeks,
  • or the tokens come from another company's login system.

This isn't "always use refresh tokens". It's what you add once you've chosen JWTs and still want logout to mean something.

So Far, the Shop Makes Its Own Tokens#

In everything above, our shop checks Alice's password and makes the tokens itself.

But what happens when Alice clicks "Sign in with Google"? Now a different company checks who she is, and our shop has to trust tokens it didn't make. That's OAuth and OpenID Connect, and it's Part 3.

32 logins a day was never the price of being safe. Give every request a short token, keep the long one at the front desk, and Alice almost never has to type her password.

Further Reading#

Vibhavari Bellutagi

Vibhavari Bellutagi

Data and Backend Engineer. 10+ years in software, seven of them building data platforms (Spark, Kafka, Databricks) at Deloitte, AgileLab and Mews. Alongside that, I build the backends of my own projects and write up the hard parts here.