Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 30 ยท Projects and Practice

Project: testing a login and token-refresh flow

Test the full token lifecycle: login, short-lived access tokens, expiry, a refresh script in Postman, token rotation and the negative auth tests that matter.

Almost every real API puts a login in front of its data, and most of them use short-lived access tokens so that a stolen token stops working quickly. That design creates a small lifecycle that is easy to get wrong and hard to test by hand: log in, use the token, wait, watch it expire, trade a refresh token for a new one, and make sure old or forged tokens are refused.

In this project you will test exactly that lifecycle. You will see what the server must do, write the Postman pre-request script that keeps a token fresh automatically, and design the negative tests that catch security mistakes. The real Postman script is read-only (it needs a real server). The runnable examples are stand-ins: an authentication server written as plain functions, with a fake clock so you can jump ahead in time instantly instead of waiting a minute for a token to expire.

The token lifecycle

The flow has three endpoints. Their names vary between systems; these are the ones used here.

Endpoint Input Success Failure
POST /auth/login username and password 200 with an access token, a refresh token and expires_in 401 invalid_credentials
POST /auth/refresh a refresh token 200 with a new pair of tokens 401 if the refresh token is unknown or already used
GET /profile Authorization: Bearer <access token> 200 with the user 401 for a missing, unknown or expired token

One session, five moments

Login Trade a password for two tokens.
Use Send the access token on each call.
Expire After about a minute it stops working.
Refresh Trade the refresh token for a new pair.

Short access tokens limit the damage if one leaks.

1 / 2

The second slide describes refresh-token rotation: every successful refresh hands out a new refresh token and retires the old one. If someone replays a retired token, either a thief or the real user is holding a stale copy, and a careful server treats the replay as a warning and revokes the session. Not every system does this, so confirm your own server's rules before asserting it.

The stand-in authentication server

The code below models those three endpoints as functions. Time comes from a clock object you control, so clock.advance(61) instantly makes a 60-second token old. Tokens are simple counters here (acc-1, ref-1) to keep output readable; real tokens are long, random or signed values.

Run it and follow the story in the log: a failed login, a successful one, calls before and after expiry, a refresh, and a replay of the retired refresh token.

Node.js Walk through the whole token lifecycle

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.

Notice what the log proves. The token works right up to the edge of its lifetime and fails exactly after it, with a specific error (token_expired, not just invalid_token), which lets a client know that refreshing is the right reaction. The replay of ref-1 is rejected, and the server's response to that replay is to revoke the session entirely.

Keeping a token fresh in Postman

If every request in your suite needed a manual login first, the suite would be useless. The standard answer is a pre-request script on the collection: before each request runs, the script checks whether the stored access token is still good, and fetches a new one if it is not. The script is read-only here, because it sends real requests:

JavaScript
const skewMs = 10 * 1000; // refresh a little early
const expiresAt = Number(pm.environment.get("expires_at") || 0);
const hasToken = Boolean(pm.environment.get("access_token"));

if (!hasToken || expiresAt - Date.now() <= skewMs) {
  pm.sendRequest(
    {
      url: pm.environment.get("base_url") + "/auth/refresh",
      method: "POST",
      header: { "Content-Type": "application/json" },
      body: {
        mode: "raw",
        raw: JSON.stringify({ refresh_token: pm.environment.get("refresh_token") }),
      },
    },
    (error, response) => {
      if (error || response.code !== 200) {
        console.error("Refresh failed. Run the Login request first.");
      } else {
        const data = response.json();
        pm.environment.set("access_token", data.access_token);
        pm.environment.set("refresh_token", data.refresh_token);
        pm.environment.set("expires_at", Date.now() + data.expires_in * 1000);
      }
    }
  );
}

Three details deserve attention. The skew (here ten seconds) avoids a race where the token is valid when the script checks and expired when the server receives the request. The new refresh token must be stored, because with rotation the old one is now useless. And the Login request's own test script should store the first set of tokens and expires_at in the same way. The tools used here are covered in Pre-request scripts and Environments and variables.

The next stand-in reproduces the same decision logic against the fake server, and then runs the negative tests. The ensureToken function mirrors the Postman script: reuse the token if it has more than the skew left, otherwise refresh, and if refreshing fails, log in again.

Negative auth tests

A passing login is the easy half. The tests that find real vulnerabilities are the ones that present something wrong and insist on a refusal. For this flow, the list is short and valuable:

  1. Wrong password, expecting 401.
  2. No Authorization header, expecting 401.
  3. A made-up token, expecting 401.
  4. An expired token, expecting 401 with the expiry reason.
  5. A reused refresh token, expecting 401 (and, if the system promises it, revocation of the session).
  6. A refresh with garbage, expecting 401.

Also check what the error bodies do not say. A login failure that reveals "no such user" versus "wrong password" lets an attacker discover which accounts exist, so both cases should look the same. (More on this in Security testing basics for APIs.)

Node.js Auto-refresh logic and the negative tests

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.

In the first part, six calls spread over time cost only one login and a couple of refreshes: when the token has plenty of life the script does nothing, which keeps the suite fast and avoids hammering the login endpoint. The call at t+155s is the instructive one: after a 100-second gap the access token had expired, but the refresh token was still valid, so the script refreshed instead of logging in again. The call at t+55s refreshed too, even though the token had not quite expired, because fewer than ten seconds of life were left.

Putting it into a collection

Structure the real collection like this: a Login request that stores access_token, refresh_token and expires_at; a collection-level pre-request script (the one above); and the protected requests, which simply inherit Bearer {{access_token}}. Keep the negative tests in their own folder and make each one override authentication on the request, so they exercise the refusal paths without disturbing the shared token. Chaining details are in Chaining requests and workflows.

Never put real production passwords or long-lived refresh tokens in a collection that others can see. Keep them in the current value of a private environment, as explained in the variables lesson, and use a dedicated test account.

The server above is a stand-in: its tokens are counters, it has no HTTP layer and the clock is fake. What carries over is the lifecycle, the refresh decision (including the skew) and the list of negative cases.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do many APIs use short-lived access tokens together with refresh tokens?

    Short access tokens limit the damage if one leaks, and the long-lived refresh token is sent only to the refresh endpoint.
  2. 2. Why does the refresh script include a small 'skew' (for example 10 seconds)?

    Refreshing slightly early prevents the race where the token expires in transit between the script and the server.
  3. 3. With refresh-token rotation, what should happen if a retired refresh token is used again?

    A replay suggests a copied token, so the request is refused and many systems revoke the user's refresh tokens as a precaution.
  4. 4. Why test that an unknown user and a wrong password give the same login response?

    Different messages let an attacker discover valid usernames. Identical responses reveal nothing.
  5. 5. How does a fake clock help when testing token expiry?

    Controlling time makes expiry tests quick and repeatable; against a real server you instead use a very short token lifetime in a test environment.

Summary

  • The token lifecycle is login, use, expiry, refresh and (with rotation) replacement of the refresh token.
  • A collection-level pre-request script keeps the token fresh: reuse it if it has more than a small skew left, otherwise refresh, and log in again if refreshing fails.
  • Store the new refresh token after every refresh, or the next refresh will fail.
  • Write negative tests for wrong credentials, missing, forged and expired tokens, reused refresh tokens and garbage input.
  • Check that error responses do not leak information, such as which usernames exist.
  • Control time in stand-ins with a fake clock; against a real server, use a short token lifetime in a test environment.
  • The runnable code is a stand-in authentication server, not a real identity provider.

Next: Project: automated regression in CI.