SiteTidy
HomeGuidesImplementing OAuth 2.0 (Part 3): Access Tokens, Refresh Tokens and Session Security
Security

Implementing OAuth 2.0 (Part 3): Access Tokens, Refresh Tokens and Session Security

Design OAuth tokens that survive real production threats. Learn bearer-token risk, refresh-token rotation, JWT validation, opaque tokens, sender-constrained tokens, revocation and secure storage.

Published on August 15, 2026Updated August 31, 2026
Implementing OAuth 2.0 (Part 3): Access Tokens, Refresh Tokens and Session Security

OAuth implementations rarely fail because somebody forgot what an access token is. They fail because the token lifecycle was designed as an afterthought.

A token is a credential. If an attacker gets a usable bearer token, the fact that your login page has MFA, CAPTCHA and a beautifully implemented PKCE flow is suddenly much less relevant. The resource server normally sees a valid credential and does exactly what it was designed to do.

That is why a secure OAuth deployment has to answer more than “how do we obtain a token?” It needs clear decisions about what each token represents, where it can travel, where it can be stored, how long it remains useful, how it is validated and what happens when it is stolen.

This part focuses on that lifecycle.

Access tokens and refresh tokens solve different problems

An access token is presented to a resource server — usually an API — as evidence that a client has authority to perform some operation.

A refresh token is presented to the authorization server to obtain a new access token without forcing the user through the full authorization interaction again.

That difference matters because the two credentials should generally have different exposure profiles.

A short-lived access token may cross the network repeatedly as API calls are made. A refresh token should normally travel far less often and should never be sent to ordinary resource APIs.

A useful mental model is:

Browser / app
    │
    │ authorization code
    ▼
Authorization server
    │
    ├── access token  ───────────────► Resource API
    │
    └── refresh token ──┐
                        │
                        └────────────► Authorization server only

If your application is sending refresh tokens to your API because “they are both tokens”, the design needs fixing.

Bearer tokens are deliberately simple — and that is the risk

The common OAuth model uses bearer tokens. The bearer is whoever possesses the token.

That simplicity is useful. APIs do not need to know how the user authenticated or which login UI they used. They receive a credential, validate it, check its permissions and continue.

But possession is enough. A stolen bearer token can usually be replayed by an attacker until it expires or is revoked.

That means the first line of token security is not clever cryptography. It is reducing opportunities for tokens to leak.

Typical leak paths include:

  • browser storage compromised by XSS;
  • tokens written into application logs;
  • tokens appearing in URLs or query strings;
  • debugging output copied into tickets or chat;
  • analytics and telemetry capturing request headers or page state;
  • mobile backups containing insecurely stored credentials;
  • secrets accidentally committed to source control;
  • malicious browser extensions;
  • compromised CI/CD or support tooling;
  • reverse proxies that log Authorization headers;
  • tokens copied into screenshots and documentation.

Treat access tokens as secrets even when they are short-lived.

Short-lived access tokens limit the blast radius

An access token should normally expire reasonably quickly.

There is no universal magic lifetime. A five-minute token may be appropriate for a high-risk financial API and irritatingly short for an intermittently connected mobile application. A 24-hour bearer token may be operationally convenient and unnecessarily dangerous for an administrative control plane.

The design question is:

If this access token leaks now, how long am I comfortable with an attacker being able to use it without obtaining another credential?

Shorter lifetimes reduce that window, but they shift more responsibility onto refresh-token handling and availability of the authorization server.

Do not make access tokens effectively permanent just to avoid implementing refresh properly.

Refresh tokens deserve stronger protection than access tokens

Refresh tokens can often mint replacement access tokens repeatedly. That makes them extremely attractive credentials.

The current OAuth Security Best Current Practice requires public clients to protect refresh tokens against replay using sender-constrained refresh tokens or refresh-token rotation.

Refresh-token rotation works by replacing the refresh token every time it is used:

Client has RT-1
      │
      │ refresh
      ▼
Authorization server
      │
      ├── AT-2
      └── RT-2

RT-1 is now invalid

The client must discard RT-1 and store RT-2.

The interesting part happens when an old refresh token is seen again.

Suppose malware stole RT-1 before the legitimate client used it. The legitimate client refreshes and receives RT-2. Later, the attacker tries RT-1. The authorization server can detect that a rotated token has been replayed.

A robust implementation can then revoke the affected refresh-token family and force re-authentication rather than silently issuing credentials to both parties.

Rotation is not simply “change the string occasionally”. You need server-side state sufficient to detect reuse.

Rotation introduces race conditions — design for them

Real clients are concurrent.

A browser may have multiple tabs. A mobile application may make several requests at startup. Two API calls can discover an expired access token at almost the same moment and both attempt a refresh.

Naive rotation code creates this failure:

Request A uses RT-7 -> succeeds -> receives RT-8
Request B uses RT-7 -> looks like replay -> session revoked

The second request is legitimate, but it looks indistinguishable from reuse unless your architecture handles concurrency.

Solutions vary by platform, but common patterns include:

  • serialize refresh operations in the client;
  • use a single token-management component rather than letting every request refresh independently;
  • allow a very small server-side grace strategy where appropriate;
  • treat the first successful refresh as authoritative and distribute the new token safely;
  • avoid storing independently diverging refresh state across browser tabs.

Do not discover this problem after users start being randomly logged out in production.

Where should browser applications store tokens?

This is one of the most argued-about OAuth questions because there is no storage location that magically defeats every browser threat.

JavaScript-readable storage

localStorage, sessionStorage and ordinary JavaScript variables can all be reached by JavaScript running in the application’s origin under the right circumstances.

If an attacker achieves XSS, a token sitting in localStorage can be stolen directly.

Keeping a token only in memory reduces persistence and can make opportunistic theft harder, but malicious JavaScript executing in the page may still be able to call APIs as the user or read in-memory values.

HttpOnly cookies

An HttpOnly cookie cannot be read directly by JavaScript, which removes a valuable token-exfiltration path.

However, cookies introduce their own browser security concerns because they are attached automatically to matching requests. You therefore need appropriate Secure, HttpOnly and SameSite settings plus proper CSRF protections where the application architecture requires them.

This is one reason a backend-for-frontend (BFF) architecture is attractive for many browser applications. The browser holds an application session cookie while the server-side BFF holds OAuth tokens.

Browser
  │
  │ Secure HttpOnly session cookie
  ▼
BFF
  │
  │ OAuth access token
  ▼
API

Now the browser does not need direct access to the OAuth refresh token at all.

That is not automatically the right architecture for every SPA, but it is a powerful way to reduce token exposure.

Native apps need platform-secure storage

A native application cannot keep a true client secret merely because somebody embedded one in the application package. Anything shipped to an end-user device should be treated as recoverable by a sufficiently motivated attacker.

That is why native apps are public clients and why Authorization Code + PKCE is important.

For token persistence, use the platform’s protected credential storage rather than a plaintext preferences file or ordinary database:

  • iOS Keychain;
  • Android Keystore-backed secure storage;
  • OS credential stores on desktop platforms where available.

Even then, assume a rooted, jailbroken or compromised device may expose credentials. Token lifetime, rotation and server-side anomaly detection still matter.

JWT access tokens are not inherently better than opaque tokens

A common mistake is treating “JWT” as a synonym for “modern OAuth”.

OAuth does not require access tokens to be JWTs.

An opaque token may simply be an unpredictable identifier that the resource server validates through local server state or token introspection.

A JWT access token carries signed claims that a resource server can validate locally.

Both approaches are legitimate.

JWT access tokens can be useful when:

  • multiple distributed APIs need independent validation;
  • avoiding a validation network round-trip matters;
  • authorization metadata needs to travel with the token;
  • the authorization server and resource server are operationally separate.

Opaque tokens can be attractive when:

  • centralised revocation/control is important;
  • you do not want client-visible authorization claims;
  • token structure should remain an implementation detail;
  • the resource server can efficiently introspect or resolve the token.

The wrong question is “Should we use JWT because JWT is scalable?”

The better question is “Which validation and revocation model do our resource servers need?”

If you use JWT access tokens, validate them as access tokens

A JWT is a container format, not proof that a request is authorized.

A resource server needs to validate more than “the signature parsed successfully”.

For an OAuth JWT access token, validation commonly includes:

  • signature verification using an allowed algorithm;
  • issuer (iss);
  • audience (aud) for the API receiving it;
  • expiry (exp);
  • not-before (nbf) where present;
  • token type/profile expectations;
  • scopes or authorization claims required for the operation;
  • any sender-constraining information where used.

The standardized JWT access-token profile in RFC 9068 also defines a dedicated access-token type (at+jwt). Explicit typing helps reduce dangerous confusion between different JWT classes.

That matters because ID tokens and access tokens are not interchangeable.

An ID token tells an OpenID Connect client about an authentication event and user identity. It is intended for the client.

An access token is intended for a resource server.

Do not accept an ID token at an API merely because both happen to be signed JWTs from the same issuer.

Audience validation stops one API’s token becoming another API’s token

Consider two APIs:

https://api.example.com/orders
https://admin.example.com/

If the orders API accepts any correctly signed token from the issuer without checking the audience, a token minted for another service may be incorrectly accepted.

That is a class of authorization failure hidden behind perfectly valid cryptography.

Every resource server should know which tokens are intended for it.

Signature validation answers:

Did a trusted issuer sign this token?

Audience validation answers:

Did that issuer create this token for me?

You generally need both.

Scopes should describe delegated capability, not become your entire authorization model

Scopes are useful for expressing broad delegated permissions such as:

orders:read
orders:write
profile
calendar.read

But applications often push too much fine-grained business authorization into token claims.

Imagine a token containing a cached list of 2,000 customer IDs the user may access. What happens when an administrator removes access to one customer five seconds after the token is issued?

The API may continue accepting stale authorization data until the token expires.

Use token claims for information that tolerates the token’s lifetime. Perform dynamic authorization against authoritative application data when decisions need to change immediately.

Revocation is useful, but it does not make long-lived bearer tokens harmless

OAuth defines token revocation mechanisms, but revocation behaviour depends on your architecture.

An opaque token checked against central state can often be invalidated quickly.

A self-contained JWT validated entirely offline may remain acceptable to a resource server until its expiry unless the system introduces additional revocation state or key changes.

That is one reason short access-token lifetimes remain valuable even when refresh tokens can be revoked.

Think in terms of layers:

short access-token lifetime
+ refresh-token rotation/revocation
+ logout/session revocation
+ anomaly detection
+ sender constraining where justified

No single control needs to carry the entire system.

Sender-constrained tokens reduce replay value

Bearer tokens work for whoever possesses them. OAuth also supports sender-constrained tokens, where possession of the token alone is insufficient.

Current OAuth security guidance points to two established mechanisms:

  • mutual-TLS certificate-bound access tokens (mTLS);
  • Demonstrating Proof of Possession (DPoP).

DPoP

DPoP lets a client prove possession of a private key by signing a proof JWT for requests. The authorization server can bind the issued token to the client’s public key.

When the token is later presented to an API, the client also sends a fresh DPoP proof. A stolen token without the corresponding private key is therefore much less useful.

Conceptually:

stolen bearer token
      │
      └── attacker can replay it

stolen DPoP-bound token
      │
      └── attacker also needs the bound private key

DPoP adds complexity — key generation, proof validation, replay prevention, clock handling and server support — so it should be deployed intentionally rather than sprinkled onto an architecture as a buzzword.

mTLS

Mutual TLS can bind tokens to a client’s certificate. It is particularly relevant in higher-assurance server-to-server and regulated environments where certificate lifecycle management is already part of the platform.

Again, the benefit is replay resistance: the resource server can require the certificate associated with the token.

Never put access tokens in URLs

Tokens in query strings or URL fragments can leak into places you did not intend:

  • browser history;
  • proxy logs;
  • server logs;
  • screenshots;
  • monitoring products;
  • copied links;
  • referrer information in some flows.

Use the Authorization header for API bearer tokens:

Authorization: Bearer eyJ...

And configure your infrastructure so sensitive authorization headers are not casually logged.

Check the public security surface around your authentication flow

SiteTidy can inspect HTTPS, security headers and other exposed web configuration. It does not replace OAuth testing, but it can catch surrounding deployment mistakes that weaken an otherwise sound implementation.

Run Free Audit →

Logout is a token-lifecycle operation, not just a UI redirect

A surprising number of systems implement logout as:

window.location = '/login';

That changes the screen, not the credentials.

A proper logout design should consider:

  • deleting the local application session;
  • revoking refresh tokens where appropriate;
  • clearing server-side session state;
  • whether the identity-provider session should also end;
  • whether access tokens remain usable until their short expiry;
  • multiple devices and sessions;
  • back-channel/front-channel logout if your OpenID Connect architecture supports them.

Be explicit about what “log out” means in your product. Logging out this browser is not necessarily the same as revoking every session on every device.

A practical token design for a web application

A common production architecture might look like this:

Browser
  │
  │ Secure + HttpOnly + SameSite session cookie
  ▼
Backend / BFF
  │
  ├── keeps OAuth tokens server-side
  ├── rotates refresh tokens
  ├── refreshes access tokens when required
  └── applies CSRF protection to browser requests
  │
  ▼
API
  │
  ├── validates issuer
  ├── validates audience
  ├── validates expiry
  ├── checks scope / authorization
  └── records security-relevant failures

This is not the only valid design. A native app or a pure public SPA has different constraints. What matters is that the storage and token lifecycle follow from the threat model rather than convenience.

Token failures you should test deliberately

Do not stop testing at “valid token returns 200”.

Your API should be exercised with:

  • expired access token;
  • token issued by the wrong issuer;
  • token for the wrong audience;
  • token with insufficient scope;
  • malformed token;
  • validly structured but incorrectly signed JWT;
  • ID token presented as an access token;
  • revoked/rotated refresh token;
  • replayed old refresh token;
  • concurrent refresh attempts;
  • missing DPoP proof where DPoP is required;
  • replayed DPoP proof;
  • logout followed by refresh attempt.

Authentication code often looks solid when only the happy path is tested.

A production checklist for OAuth tokens

Before calling the token layer complete, you should be able to answer all of these:

  • What is the access-token lifetime, and why?
  • Where can an access token be stored?
  • Where can a refresh token be stored?
  • Can either appear in logs, telemetry or URLs?
  • Are public-client refresh tokens rotated or sender-constrained?
  • What happens when refresh-token reuse is detected?
  • How does the client avoid concurrent refresh races?
  • Are JWT access tokens validated for issuer and audience, not just signature?
  • Can an API accidentally accept an ID token?
  • How are scopes converted into real application authorization decisions?
  • How quickly can a compromised session be revoked?
  • What exactly happens at logout?
  • Are sender-constrained tokens justified for the application’s risk level?

If any answer is “we let the identity library decide”, inspect the library configuration. Good libraries remove protocol plumbing; they cannot choose your threat model for you.

The point of token security

A secure OAuth deployment assumes credentials can eventually leak.

That sounds pessimistic, but it leads to better engineering.

Short-lived access tokens limit usefulness. Refresh rotation reveals replay. Strong storage reduces exposure. Correct audience validation prevents cross-service misuse. Revocation ends renewable sessions. Sender-constraining can make stolen tokens materially harder to replay.

The goal is not to invent an unstealable token. It is to ensure that one leaked string does not quietly become unrestricted, long-lived access to your system.

In Part 4, we move up a level and choose the right OAuth architecture for the client you are actually building: server-rendered web apps, browser SPAs, BFFs, native applications, machine-to-machine services and devices.

Ready to audit your site?

Put this guide into practice immediately using our free tools.

Browse 180+ Free Tools