Access Tokens, Refresh Tokens, and Login State

Design short-lived access, refresh rotation, logout, and client behavior after expiration

🎯 Introduction

By the end of this article, you will be able to coordinate refresh after access token expiration and handle refresh failures, concurrent refreshes, and logout.

⏱ Access tokens authenticate API requests

An access token is a credential sent to protected endpoints. For example, after login returns a token valid for 15 minutes, include it in the header when requesting a profile:

GET /me HTTP/1.1
Authorization: Bearer <access-token-from-login>

The server verifies the token and returns the profile, or returns 401 for invalid or expired credentials. Replace the placeholder with the actual login response value. Tokens can use JWTs, as introduced earlier, or random credentials backed by server-side records.


🔑 Refresh tokens extend login

A refresh token obtains a new access token. It typically lasts longer, for example seven days, so users do not need to reenter their passwords every 15 minutes.

Send refresh tokens only to the refresh endpoint, not with every business request. Browser apps can store them in Secure, HttpOnly cookies to reduce direct page script access. Cookie-authenticated refresh endpoints still need CSRF protection, such as checking request origins.

Choose lifetimes according to business risk. Access token expiration and final login session expiration are separate events. Users must log in again once the refresh session expires.


🔄 Refreshing after a 401

Here, /auth/refresh is the project's refresh endpoint, with the refresh credential stored in a cookie. After an access token failure causes a business request to return 401, the frontend sends:

POST /auth/refresh HTTP/1.1
Cookie: refresh=<current-refresh-credential>

The server checks whether the refresh record exists, has expired, or was revoked. If valid, it returns a new access token. With refresh rotation, it also updates the refresh credential through Set-Cookie. For example, the response body is:

{"accessToken":"new-access-token","expiresIn":900}

expiresIn is the remaining lifetime of the new access token in seconds. The frontend saves the new value and retries the original business request once. When integrating an authentication service, follow its refresh URL, credential transport, and response field contract.


🗃 Persist login records so logout takes effect

Suppose user 1 logs in on a phone. The server stores a record owned by user 1, expiring in seven days, and not currently logged out. The refresh endpoint looks it up using the credential and issues a new access token only while the record remains valid.

On logout, mark this record as logged out. Submitting the old refresh token then returns 401. A computer can have a separate login record, so logging out the phone need not log out the computer.

Store records in a database or another location that survives restarts. Store a digest—a verification value derived from the refresh credential—and compute it the same way on refresh to find the record. This avoids storing raw credentials that could be used directly to log in.


🔁 Replace refresh credentials after every refresh

Refresh rotation issues a new refresh token on successful refresh and stops accepting the old one. Submitting R1 returns a new access token and replaces R1 with R2 through Set-Cookie. Only R2 is accepted next time.

A copied R1 therefore cannot continue obtaining access tokens after it has been used. If the old value appears again, the authentication scheme determines whether to revoke the login and require authentication again.

If two requests submit R1 concurrently, only one may replace the credential successfully. The authentication service must perform this check and update together. The frontend should also avoid concurrent refreshes as described below.


🖥 What if several endpoints expire together?

A page may request a profile, messages, and permissions simultaneously. If all return 401, start one refresh and let the other requests wait for its result.

Refresh resultClient action
SuccessUpdate the access token and retry each original request once
Refresh returns 401Clear local login state and prompt login
Refresh network failureReport a connection problem and avoid endless automatic retries
Business endpoint returns 403Display insufficient permissions; refreshing does not resolve it

If an original request still returns 401 after successful refresh, stop retrying to avoid a loop. The frontend coordinates requests; it cannot extend a server token's lifetime itself.


🚪 Logout must update both sides

The logout endpoint revokes the current login's refresh record and clears the browser cookie. The frontend also clears its in-memory access token. Subsequent refresh requests return 401.

Deleting a refresh record does not automatically invalidate an issued JWT. If logout must immediately reject old access tokens, endpoints need an additional session revocation check. Otherwise, the token may remain usable until its own expiration.

Password changes or account suspension should also revoke other login sessions as required by the application, rather than only logging out the current page.


❓ Questions and Answers

Q1: Must session-based websites introduce both token types?

No. Ordinary session login can manage state through session expiration. The two-token approach is for projects that need this authentication flow.

Q2: Can I avoid refresh by making access tokens very long-lived?

That also increases their usable lifetime after a leak. Choose expiration according to risk rather than merely reducing requests.

Q3: Does refresh failure mean the password is wrong?

Not necessarily. The refresh credential may have expired, been revoked, or been reused. The client should decide whether to request login based on the refresh result.


🧪 Practice

Draw the sequence when two requests return 401 together. Mark one refresh, two original request retries, and where login state is cleared if refresh fails.

// Record the processing steps here