# Guide to Auth Tokens

You log in to a shopping app, check your orders, update your address, and close the tab. When you return later, the app still knows who you are.

We expect this to work. But building it raises some interesting questions.

How does the server recognize you after login? Where should the browser keep your credentials? What happens if someone steals them? And when you click **Log out**, are you really logged out everywhere?

To answer those questions, we need to understand access tokens, refresh tokens, cookies, and CSRF protection and how they work together.

## 1\. Why do we need tokens at all?

HTTP is stateless. Each request is independent. The protocol does not automatically connect your login request to the request you make a minute later.

Suppose you log in and then request `/api/orders`. Your application needs some way to prove that both requests belong to the same user.

You could send your email and password with every request, but that creates problems:

- Your password passes through application code and infrastructure repeatedly, increasing opportunities for accidental exposure.
- Password verification is deliberately expensive. Algorithms such as bcrypt and Argon2 are designed to make guessing passwords costly. Running that verification for every API call wastes resources.
- A stolen password remains useful until it changes.
- The password alone cannot distinguish your laptop from your stolen phone.
- Your main password is a poor credential to give another application for limited access.

Instead, the server verifies your password during login and gives you another credential to use afterward.

That credential is a token.

It lets the application manage your logged-in access without repeatedly handling your password.

## 2\. Server-side sessions and self-contained tokens

Before we get into JWTs, one detail is worth clearing up: a session ID is also a token.

The distinction is where the information lives.

With a server-side session, the client holds an unpredictable identifier. The server uses that identifier to look up the user’s session in a database or cache.

With a self-contained token, the client holds a credential containing information the server can verify directly.

| Approach | What the client holds | How the server checks it | Main trade-off |
| --- | --- | --- | --- |
| Server-side session | A random session ID | Looks up the session in a shared store | Straightforward revocation, but requires session storage |
| Signed JWT | A token containing signed claims | Verifies the signature and validates the claims | Can avoid session lookups, but immediate revocation needs additional checks |

Server-side sessions work well for many browser applications. JWTs can be useful when several services need to validate credentials independently.

Neither is automatically more secure or more modern. The right choice depends on your application.

For this guide, we’ll use JWT access tokens and server-managed refresh sessions.

## 3\. What is an access token?

An access token is a credential that allows a client to call a protected API.

Think about the visitor pass you receive at an office. Reception checks your identity once. You then show the pass when entering the areas you are allowed to visit.

An API client presents its access token like this:

```http
GET /api/orders
Authorization: Bearer <access-token>
```

**Bearer** means that possession is enough to use the token. Someone who steals it can usually present it without knowing your password.

An access token can be an opaque random value or a structured token such as a JWT.

“Access token” describes what the credential does. “JWT” describes its format.

## 4\. What is a JWT?

A typical signed JWT contains three parts:

```text
header.payload.signature
```

The header describes the signing algorithm. The payload contains claims. The signature allows the server to verify that a trusted issuer created the token and that its contents have not changed.

A payload might look like this:

```json
{
  "sub": "user_123",
  "role": "customer",
  "iss": "https://auth.example.com",
  "aud": "orders-api",
  "exp": 1793539800
}
```

Here is what those claims mean:

| Claim | Meaning |
| --- | --- |
| `sub` | The subject, usually a user identifier |
| `iss` | The issuer |
| `aud` | The intended recipient |
| `exp` | The expiry time, as a Unix timestamp in seconds |
| `role` | An application-defined claim |

A signed JWT is not encrypted. Anyone holding it can read the header and payload.

Do not put passwords, secrets, or unnecessary personal information inside it.

Also, decoding a token is not the same as verifying it. Decoding tells you what the token claims. Verification tells you whether you can trust those claims.

## 5\. Issuing and validating an access token

Here is a small example using Express and `jsonwebtoken`.

It assumes Express is already configured and `verifyCredentials` handles password verification. This first example only covers the access token.

```js
import jwt from "jsonwebtoken";

const accessSecret = process.env.ACCESS_SECRET;

if (!accessSecret) {
  throw new Error("ACCESS_SECRET is required");
}

const issuer = "https://auth.example.com";
const audience = "orders-api";

function createAccessToken(user) {
  return jwt.sign(
    { role: user.role },
    accessSecret,
    {
      algorithm: "HS256",
      subject: user.publicId,
      issuer,
      audience,
      expiresIn: "15m",
    }
  );
}

app.post("/api/login", async (req, res) => {
  const user = await verifyCredentials(req.body);

  if (!user) {
    return res.status(401).json({
      error: "Invalid credentials",
    });
  }

  res.set("Cache-Control", "no-store");

  return res.json({
    accessToken: createAccessToken(user),
  });
});
```

The signing secret must be strong, randomly generated, and kept outside your source code.

This example uses a shared secret. Every service holding that secret can both verify and create tokens. With asymmetric signing, the issuer keeps a private signing key while other services verify tokens using a public key.

The API then checks incoming access tokens:

```js
function requireAuth(req, res, next) {
  const authorization = req.get("authorization") ?? "";
  const match = /^Bearer ([^\s]+)$/i.exec(authorization);

  if (!match) {
    return res.sendStatus(401);
  }

  let claims;

  try {
    claims = jwt.verify(match[1], accessSecret, {
      algorithms: ["HS256"],
      issuer,
      audience,
    });
  } catch {
    return res.sendStatus(401);
  }

  if (
    typeof claims !== "object" ||
    typeof claims.sub !== "string" ||
    typeof claims.exp !== "number"
  ) {
    return res.sendStatus(401);
  }

  req.user = claims;
  return next();
}
```

Checking the signature alone is not enough. Validate the expected algorithm, issuer, audience, expiry, and required claims. These options are covered in the [jsonwebtoken documentation](https://github.com/auth0/node-jsonwebtoken).

And remember: a valid token does not mean the user can access everything.

A user requesting `/api/orders/456` must still be allowed to view that particular order.

Authentication tells you who is calling. Authorization decides what they may do.

## 6\. Why access tokens should expire

Imagine someone steals an access token that remains valid for a month. Unless your API has another way to reject it, the attacker may have a month of access.

A short lifetime reduces that window.

It also limits how long outdated information remains useful. If an administrator removes someone’s role, an existing token may still carry that role until it expires.

This is where stateless validation has a limitation. An API checking only the token’s signature and claims does not automatically know that the user logged out or their account was disabled.

You can add revocation checks, a denylist, or current account-status checks. But those decisions now depend on additional information.

So it is inaccurate to say JWTs cannot be revoked. The more useful explanation is that immediate revocation requires more than checking the JWT itself.

Our example uses 15 minutes. That is a design choice, not a universal rule.

But it creates another problem: nobody wants to enter their password every 15 minutes.

## 7\. What is a refresh token?

A refresh token lets the client obtain a new access token without asking the user to log in again.

It has a different job from the access token.

| Credential | Purpose | Example lifetime |
| --- | --- | --- |
| Access token | Call protected APIs | 15 minutes |
| Refresh token | Obtain new access tokens | Up to 7 days |

The refresh token is accepted by the authentication server’s refresh endpoint. It should not grant direct access to your orders API.

It does not need to be a JWT either. A cryptographically random value is often a straightforward choice because the server already needs to manage the refresh session.

The server can store a hash of that value alongside the user, session identifier, expiry, and revocation status. The client receives the original token.

That gives each device its own session. You can revoke the session on a stolen phone without necessarily signing out the user’s laptop.

## 8\. Why refresh-token rotation matters

A long-lived refresh token is valuable to an attacker. If it stays unchanged for seven days, someone who steals it may keep requesting access tokens during that period.

Rotation means replacing it after every successful refresh.

Suppose the browser receives refresh token A. When it uses A, the server invalidates A and issues token B. The next successful refresh replaces B with C.

Now imagine A appears again.

It has already been used. Either a client retried an old request or someone has another copy.

A common security response is to revoke the associated refresh session and ask the user to log in again. This replay-detection approach is described in [OAuth’s security best current practice](https://www.rfc-editor.org/rfc/rfc9700.html#section-4.14).

Making this reliable takes care:

- Rotation must be atomic so two requests cannot both exchange the same token successfully.
- The server needs enough history to recognize used tokens and associate them with their session.
- The client must coordinate concurrent refresh requests, including those from multiple tabs.
- Lost responses and retries need a deliberate policy so normal network problems do not cause unnecessary logouts.

Also, rotating a token should not silently extend the session forever. Decide how inactivity expiry and an absolute session lifetime work.

## 9\. Where cookies fit

A cookie is a browser storage and delivery mechanism. It is not a token format.

A cookie can carry a session ID, an opaque refresh token, or a JWT.

For a same-site browser application, the server might set a refresh cookie like this:

```js
res.cookie("refreshToken", refreshToken, {
  httpOnly: true,
  secure: true,
  sameSite: "strict",
  path: "/api/auth",
  maxAge: 7 * 24 * 60 * 60 * 1000,
});
```

This example places refresh and logout endpoints under `/api/auth`.

The settings have separate responsibilities:

| Setting | Purpose |
| --- | --- |
| `httpOnly` | Prevents page JavaScript from reading the cookie |
| `secure` | Restricts transmission to HTTPS |
| `sameSite` | Controls cookie attachment in cross-site contexts |
| `path` | Limits which request paths receive the cookie |
| `maxAge` | Sets how long the browser retains it |

The server must enforce session expiry independently. A browser retaining a cookie does not make its session valid.

Cookie paths also are not security boundaries between applications sharing an origin.

`SameSite=Strict` works for some applications but can interfere with expected cross-site flows. Cross-site cookies generally require `SameSite=None; Secure`, careful CSRF protection, and consideration of browser third-party-cookie restrictions.

The behavior that matters next is automatic attachment: browsers send matching cookies without your JavaScript manually adding them.

## 10\. What is CSRF?

Suppose you are logged in to an application through a cookie.

You then visit a malicious website. That website tries to submit a request to your application, perhaps to change your email address.

Depending on the cookie settings and request context, your browser may attach your authentication cookie.

The attacker does not necessarily need to read the cookie or the response. If the server accepts the request and changes your email, the attack has already worked.

This is Cross-Site Request Forgery, or CSRF.

The application receives a request carrying your credentials, but another website caused your browser to send it.

Authentication alone does not establish that the request came through your application’s intended flow.

## 11\. How a CSRF token helps

A CSRF token is an unpredictable value that the legitimate application submits separately from automatically attached authentication cookies.

In a synchronizer-token design, the server generates a token associated with the browser session. The application receives it through a protected page or endpoint and sends it back with state-changing requests.

For example:

```js
await fetch("/api/change-email", {
  method: "POST",
  credentials: "same-origin",
  headers: {
    "Content-Type": "application/json",
    "X-CSRF-Token": csrfToken,
  },
  body: JSON.stringify({
    email: "new@example.com",
  }),
});
```

The server validates the CSRF token before making the change.

An attacker’s website generally cannot read the legitimate application’s token because of the browser’s same-origin restrictions. That assumes the application does not expose it through permissive CORS or another leak.

Another established approach is a signed double-submit cookie design that binds the CSRF token to the authenticated session.

Use your framework’s supported protection where possible. The [OWASP CSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html) explains these patterns.

A CSRF token does not identify the user or replace authentication. It provides additional protection against forged requests.

It also does not prove a human consciously approved an action. Malicious code running inside your application may still obtain it.

## 12\. Do JWTs prevent CSRF?

No. The token’s format does not determine whether CSRF is possible.

If a JWT lives in a cookie that the browser automatically attaches, cookie-based CSRF concerns still apply.

If your application explicitly adds an access token from memory to an `Authorization` header, another website normally cannot make the browser attach that token automatically. That avoids the classic cookie-based CSRF mechanism for those endpoints.

Your refresh endpoint may still use a cookie, though. It needs its own protection.

Alongside CSRF validation, use appropriate `SameSite` settings, origin checks, and carefully restricted credentialed CORS.

Do not use `GET` requests to change application state.

CORS alone is not a general CSRF defense. Some cross-origin requests can be sent even when the attacker is not allowed to read their responses.

## 13\. What about XSS?

Cross-Site Scripting, or XSS, happens when malicious JavaScript runs inside your application’s origin.

That script may be able to read application data, access browser storage, obtain CSRF tokens, and make requests through the user’s browser.

An `HttpOnly` cookie prevents JavaScript from reading the cookie directly. It does not stop malicious JavaScript from sending authenticated requests while it runs.

This is why CSRF protection and XSS prevention are separate responsibilities.

Safe rendering, contextual output escaping, sanitizing supported HTML, careful dependency handling, and a suitable Content Security Policy all help reduce XSS risk.

## 14\. Where should browser tokens be stored?

One practical design keeps the access token in application memory and the refresh token in an `HttpOnly`, `Secure` cookie.

After a page reload, the application calls the refresh endpoint to obtain a new access token. Cookie-authenticated endpoints receive appropriate CSRF protection.

Memory storage reduces persistence, but it does not make tokens immune to malicious JavaScript.

`localStorage` is convenient and survives reloads, but JavaScript running in the origin can read it. [OWASP advises against storing session identifiers there](https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html).

A server-side session or backend-for-frontend is another valid option. The browser carries a session cookie, and the backend manages any upstream tokens.

You do not need to expose JWTs to browser JavaScript just because your application calls an API.

## 15\. What logout actually means

In our access-and-refresh design, logout has three jobs:

1. Revoke the refresh session on the server.
2. Clear the refresh cookie using the matching cookie scope.
3. Remove the access token from client memory.

Revoking the refresh session stops future renewal.

A previously issued access token may still work until expiry if the API does not check revocation state. Applications requiring immediate termination need an additional server-side check or revocation mechanism.

“Log out this device” and “Log out everywhere” are different operations. One revokes a particular session; the other revokes all relevant sessions for the user.

Password changes and account recovery need explicit policies too. Changing a password does not automatically invalidate previously issued JWTs.

## 16\. Handling expired tokens without endless retries

Suppose five API calls fail because the same access token expired.

The client should coordinate one refresh operation, then let eligible requests use the new token. Sending five refresh requests can create rotation conflicts.

Retry a failed request at most once after refreshing, and avoid making the refresh request itself enter the same retry loop.

If refresh fails, clear local authentication state and ask the user to log in.

Also, do not treat every failure as an expired token. A `401` can indicate another authentication problem. A `403` generally means the caller lacks permission, which refreshing does not fix.

For requests that change data, distinguish an authentication rejection from a connection failure after the operation may already have completed. Payments and similar operations need idempotency protection against accidental duplication.

## 17\. Other tokens you will encounter

Once you work with external login providers and account recovery, more token names appear.

| Token or value | Purpose | Important detail |
| --- | --- | --- |
| ID token | Communicates an authentication result to an OpenID Connect client | Do not substitute it for an API access token |
| Authorization code | Exchanged at an OAuth token endpoint | Use PKCE to bind redemption to the initiating client |
| Password-reset token | Authorizes a password reset | Keep it short-lived, single-use, and narrowly scoped |
| Email-verification token | Confirms control of an email address | Do not grant unrelated access |
| API key | Commonly identifies an application or integration | Scope, rotate, and revoke it independently |

External login flows may also use `state` to correlate the response with the initiating browser transaction, and `nonce` to bind an OpenID Connect ID token to its authentication request.

These mechanisms address different threats. A maintained OAuth or OpenID Connect library should handle the protocol details.

The distinction between access tokens and ID tokens is covered in [OpenID Connect Core](https://www.openid.net/specs/openid-connect-core-1_0.html). Current recommendations for authorization-code flows and PKCE appear in the [OAuth security guidance](https://www.rfc-editor.org/rfc/rfc9700.html).

## 18\. How the pieces work together

At login, the server verifies credentials, creates a refresh session, issues an access token, and sets the refresh cookie.

For protected API calls, the client sends the access token. The API validates it and checks whether the user may perform the requested action.

When access expires, the client makes a coordinated refresh request. The server applies its CSRF and origin protections, validates the refresh session, rotates the refresh token, and issues a new access token.

At logout, the server revokes the refresh session and the client clears its credentials.

Throughout this process, use HTTPS, avoid logging credentials, rate-limit sensitive endpoints, and prevent authentication responses from being cached inappropriately.

The important part is understanding each credential’s responsibility. Access tokens grant temporary access. Refresh sessions control whether that access can continue. Cookies deliver credentials through the browser. CSRF protection helps defend against unwanted requests made with automatically attached credentials.

Once those responsibilities are clear, the design becomes easier to reason about especially when a token expires, a phone goes missing, or a user expects **Log out** to mean exactly what it says.
