Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
API Security APIs APIs From Zero to Real-World API Testing & Automation Authentication Module 5 — API Authentication OAuth

Token Expiration, Scopes, and Refresh Tokens — Managing API Sessions

Reviewed & accurate
AI Summary

What You'll Learn

  • Why access tokens expire quickly
  • How refresh tokens extend sessions safely
  • How scopes limit what a token can do
  • How to handle expired tokens in your client code

Why This Matters

Tokens that never expire are a security nightmare — if stolen, the thief has access forever. Tokens that expire every 5 minutes are unusable — users must re-log in constantly. The OAuth 2.0 solution is a two-token system: short-lived access tokens for security, long-lived refresh tokens for usability. Understanding this split is essential for building any authenticated app.

The Two-Token System

TokenLifetimePurposeRevocable?
Access tokenShort (15 min – 1 hour)Call the APIHard — valid until exp
Refresh tokenLong (days – weeks)Get new access tokensYes — server can revoke

Why Access Tokens Are Short-Lived

If an access token is stolen (via XSS, leaked logs, network interception), the thief has access until it expires. A 1-hour expiration limits the damage to 1 hour. A 30-day expiration gives the thief a month.

Short lifetimes also let the server change permissions quickly. If the user's role changes from admin to regular user, the next access token they get will have the new role — within an hour at most.

Why Refresh Tokens Exist

Short-lived access tokens would force users to log in every hour. That is unusable. Refresh tokens solve this:

  1. At login, the server issues both an access token (1 hour) and a refresh token (30 days).
  2. The client uses the access token for API calls.
  3. When the access token expires, the client uses the refresh token to get a new one — silently, without bothering the user.
  4. The user stays logged in for 30 days (or until they explicitly log out).

The Refresh Flow

# Access token expired — get a new one
POST /oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&
refresh_token=1//abc123&
client_id=YOUR_ID&
client_secret=YOUR_SECRET

# Response
{
  "access_token": "eyJhbGciOi...",
  "token_type": "Bearer",
  "expires_in": 3600
}

The client gets a new access token. The user is not prompted. The refresh token may also be rotated (a new one returned with each refresh) for added security.

Why Refresh Tokens Are Revocable

Unlike JWTs (which are stateless and cannot be revoked before exp), refresh tokens are stored server-side. When the user clicks "Log out" or "Revoke access", the server deletes the refresh token. The current access token is still valid until it expires (an hour at most), but no new ones can be issued.

Scopes — Limiting What a Token Can Do

Scopes are permissions attached to a token. They tell the API what the token's holder is allowed to do.

How scopes are requested

GET /oauth/authorize?
  response_type=code&
  client_id=YOUR_ID&
  scope=read:user user:email&    ← requested scopes
  ...

How scopes appear in tokens

JWTs often include scopes in the payload:

{
  "sub": "123",
  "scope": "read:user user:email",
  "exp": 1724557200
}

How the API checks scopes

# Pseudocode
def delete_post(user, post_id):
    if "write:posts" not in user.token.scopes:
        return 403 Forbidden
    # ... proceed with delete

Handling Expired Tokens in Client Code

Real clients must handle the case where the access token expires mid-session:

// JavaScript example
async function callApi(url) {
  let response = await fetch(url, {
    headers: { "Authorization": `Bearer ${accessToken}` }
  });

  if (response.status === 401) {
    // Access token may have expired — try refreshing
    const newToken = await refreshAccessToken();
    if (newToken) {
      accessToken = newToken;
      // Retry the original request
      response = await fetch(url, {
        headers: { "Authorization": `Bearer ${accessToken}` }
      });
    } else {
      // Refresh failed — user must log in again
      redirectToLogin();
      return;
    }
  }

  return response;
}

async function refreshAccessToken() {
  const response = await fetch("/oauth/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "refresh_token",
      refresh_token: refreshToken,
      client_id: CLIENT_ID
    })
  });

  if (response.ok) {
    const data = await response.json();
    return data.access_token;
  }
  return null;
}

Token Storage — Where to Keep Tokens

StorageProsCons
localStorageEasy to access from JSVulnerable to XSS
HttpOnly cookieJS cannot read — safe from XSSVulnerable to CSRF (mitigate with SameSite)
In-memory (JS variable)Lost on page reloadMost secure — use with refresh tokens in HttpOnly cookies
SessionStorageCleared when tab closesVulnerable to XSS

For high-security apps: store refresh tokens in HttpOnly cookies, keep access tokens in memory only. The user stays logged in (refresh works), but a stolen access token dies when the page closes.

Common Mistakes

  1. Long-lived access tokens. A 30-day access token is a 30-day security risk. Use 1-hour access tokens + 30-day refresh tokens.
  2. Not handling 401. If your client does not refresh on 401, users must re-log in every hour.
  3. Refreshing on every request. Wastes server resources. Only refresh when you get a 401.
  4. Storing refresh tokens in localStorage. A single XSS hole gives attackers long-lived access. Use HttpOnly cookies.
  5. Not rotating refresh tokens. If a refresh token is stolen, it works for 30 days. Rotate it on each use so the stolen one becomes invalid.
  6. Requesting too many scopes. Users will deny the login. Ask for the minimum.

Practical Exercise (10 minutes)

Decode a JWT (use jwt.io) and find:

  1. The exp claim. Convert it to a human-readable date.
  2. The scope or scopes claim. List the scopes.
  3. The iat (issued at) claim. How long is the token valid?

Then design the refresh strategy: when does your client refresh? What happens if the refresh fails? When does the user have to log in again?

Mini Challenge

Build a simple client that: (1) gets an access token and refresh token from a login endpoint, (2) makes an API call, (3) waits for the access token to expire (or shortens the expiration for testing), (4) automatically refreshes and retries. Test that the user is not interrupted.

Key Takeaways

  • Access tokens are short-lived (1 hour) for security. Refresh tokens are long-lived (30 days) for usability.
  • Refresh tokens are stored server-side and revocable. Access tokens (JWTs) are stateless and cannot be revoked before exp.
  • Scopes limit what a token can do. Always request the minimum.
  • Handle 401 in your client: try to refresh, retry, redirect to login if refresh fails.
  • Store refresh tokens in HttpOnly cookies. Keep access tokens in memory for high-security apps.
Course continuity
Previously: Lesson 30 introduced OAuth 2.0.
Today: You learned the day-to-day reality of token management — expiration, refresh, and scopes.
Next: Module 5 is complete. Module 6 begins with lesson 32 — What Is API Testing?.

FAQ

What is the difference between logout and revoke?

Logout is what the user does — they end their session in the client. The client discards its tokens. Revoke is what the server does — it invalidates the refresh token so it cannot be used to get new access tokens. A proper logout calls the revoke endpoint, otherwise the refresh token remains valid until it expires.

Should I rotate refresh tokens?

Yes. Each time you use a refresh token, the server should issue a new one and invalidate the old. This means a stolen refresh token becomes useless after the legitimate user refreshes. Implemented by OAuth providers like Google and Auth0.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments