API Security
.
12
Mins Read

Token-Based Authentication: How It Works and When to Use It

Every API call needs proof of who's calling, and tokens are how modern APIs get it. This guide explains how token-based authentication works, the token types you'll meet, tokens vs sessions, how to validate, refresh and revoke tokens, and when to use them, with tested code.

Dhayalan Subramanian
Associate Director - Product Growth at DigitalAPI
.
20 November 2026
In this blog
Share blog
TL;DR:

What is token-based authentication?

Token-based authentication is a way for a client to prove who it is by sending a token, a string issued by an authorization server, with each request instead of a password or session cookie.

The API checks the token, either by verifying its signature or by asking the server that issued it, then allows or denies the call.

Tokens expire, can be refreshed, and can be revoked.

In 2024, developers pushed 23.8 million new secrets, such as API keys and tokens, to public GitHub repositories, according to GitGuardian's State of Secrets Sprawl 2025 report. The same report found that 70% of secrets leaked in 2022 were still valid two years later.

That's the trade-off at the heart of token-based authentication. Tokens let any app, service or AI agent call an API without sharing a password. They also work for whoever holds them, so how long they live, what they allow and how fast you can kill them decide how much a leak costs you.

This guide explains how token-based authentication works, the token types you'll meet, how it compares with sessions, and how to validate, refresh and revoke tokens, with code we ran and tested.

Token-based authentication infographic showing a client getting a token from an authorization server, sending it to an API in the Authorization header, the API validating it, and the token expiring, refreshing or being revoked

What is token-based authentication?

Token-based authentication is an authentication method where the client sends a token with each request to prove its identity, instead of sending credentials every time. The token is issued once, after the client signs in or proves who it is, and is then reused until it expires.

Definition

Token-based authentication

Token-based authentication is a stateless authentication method in which a trusted server issues a time-limited token after verifying a user, application or device, and the client presents that token on each request. The receiving API validates the token's signature or asks the issuer whether it's still active, then grants access based on the identity and permissions it carries.

So what is token based authentication in everyday terms? It works like a wristband at a festival. You show your ID once at the gate, you get a wristband, and every stage after that only checks the wristband. If you lose it, whoever finds it gets in, until the wristband expires.

Is token authentication the same as a hardware token?

No. "Token" means two different things in security. In API and web security, a token is a digital string such as a JWT or an opaque access token. In multi-factor authentication, a token is a physical device or app that generates one-time codes, such as a YubiKey or an authenticator app.

Both prove identity, but they solve different problems. A hardware token proves a person is present during sign-in. An access token proves, on every API call, that sign-in already happened. This guide covers the second kind: token authentication for APIs and applications.

How does token-based authentication work?

Token-based authentication works in six steps: the client authenticates once, receives a token, stores it, sends it with every request, the API validates it, and the token eventually expires, gets refreshed or is revoked. No password crosses the network after step one.

  1. Authenticate. A user signs in, or an application proves its identity with a client secret, certificate or signed assertion.
  2. Issue. The authorization server returns an access token, often with a refresh token and an expiry time.
  3. Store. The client keeps the token somewhere safe: server memory, a secrets manager, or an HttpOnly cookie for browser apps.
  4. Present. The client sends the token on each API call, usually in the Authorization: Bearer header.
  5. Validate. The API verifies the token's signature and claims locally, or asks the authorization server whether it's active.
  6. Expire, refresh or revoke. When the token expires, the client gets a new one with its refresh token. If something goes wrong, the token is revoked.

Here's a token based authentication example. The client gets a token, then uses it:

HTTP · token request and API call
POST /oauth/token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=partner-221&client_secret=...&scope=orders:read

HTTP/1.1 200 OK
{ "access_token": "mF_9.B5f-4.1JqM", "token_type": "Bearer", "expires_in": 600, "scope": "orders:read" }

GET /orders HTTP/1.1
Host: api.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

The Bearer scheme comes from RFC 6750. It means possession is enough: anyone holding the token can use it. For more on that, see what is a bearer token.

Token-based authentication flow diagram showing the client authenticating with the authorization server, receiving an access token and refresh token, calling the API with the bearer token, the API validating it, and the client refreshing the token when it expires

What types of authentication tokens are there?

The main types of authentication tokens are access tokens, refresh tokens, ID tokens, API keys and personal access tokens. Each has a different job, lifetime and risk. Mixing them up is one of the most common token mistakes.

Types of authentication tokens

Token typeWhat it's forTypical lifetimeSent to
Access tokenCalling an APIMinutes to an hourThe API (resource server)
Refresh tokenGetting new access tokens without signing in againDays to weeks, rotatedThe authorization server only
ID tokenTelling an app who signed in (OpenID Connect)MinutesThe client app only, never an API
API keyIdentifying an application or projectMonths, until rotatedThe API
Personal access token (PAT)Letting a person's scripts act as themSet by the user, often 30 to 90 daysThe API
Hardware or OTP tokenProving a person is present during sign-in30 to 60 seconds per codeThe sign-in page

Swipe sideways to see all columns →

Two rules keep these straight:

  • Access tokens go to APIs; ID tokens go to apps. An ID token proves a sign-in to the client. Using it to call an API skips the authorization server's checks on scope and audience.
  • Refresh tokens never leave the client-to-authorization-server path. An API should never see one.

Access token vs refresh token is the pair you'll handle most: the access token is short-lived and used constantly; the refresh token is longer-lived, used rarely, and must be guarded more carefully because it can mint new access tokens. If you still rely on API keys, see our guide to API key management.

What is the difference between JWT and opaque tokens?

A JWT carries its claims inside the token and can be verified locally; an opaque token is a random string that only the issuer can look up. Both are access tokens. The choice decides how your API validates them and how fast you can revoke them.

JWT vs opaque tokens

 JWT (self-contained)Opaque token (reference)
What's insideSigned JSON claims: subject, scope, audience, expiryRandom characters, no meaning
Size in our test378 characters43 characters
How the API validates itVerifies the signature locallyAsks the issuer via introspection
Network call per requestNoYes, unless cached
RevocationWorks only when the token expires, unless you add a denylistImmediate
Readable by the clientYes, anyone can decode the payloadNo
Good forHigh-volume APIs, many services, many gatewaysHigh-risk APIs, instant revocation, privacy

Swipe sideways to see all columns →

For JWT internals, see what is a JWT. For implementing JWT sign-in end to end, see JWT authentication.

What is the difference between token-based and session-based authentication?

Session-based authentication keeps the user's state on the server and gives the browser a cookie with a session ID; token-based authentication puts what the API needs inside, or behind, a token the client presents. Sessions suit one web app on one domain. Tokens suit APIs called by many clients, services and partners.

Token-based vs session-based authentication

 Session-based authenticationToken-based authentication
Where state livesServer session storeIn the token (JWT) or the issuer (opaque)
What the client sendsA session ID cookieAuthorization: Bearer
Works across domains and APIsPoorly; cookies are tied to a domainYes
Works for machines and AI agentsNoYes
ScalingEvery server needs the session storeJWTs verify anywhere with the public key
RevocationDelete the session: instantInstant for opaque tokens; at expiry for JWTs
Main browser riskCSRFXSS if the token is readable by scripts
Best forTraditional server-rendered web appsAPIs, mobile apps, SPAs via a backend, partners, services

Swipe sideways to see all columns →

The token vs session authentication choice isn't all-or-nothing. A common, safe pattern is a backend-for-frontend: the browser holds a session cookie with the backend, and the backend holds the tokens and calls the APIs. The browser never sees an access token, and the APIs still get one.

How should an API validate tokens?

An API validates a token either locally, by checking a JWT's signature and claims, or remotely, by asking the authorization server through token introspection (RFC 7662). Local checks are fast. Introspection is slower but always current. Most APIs need to understand both.

Here's an API module that does each:

Node.js · api.mjs
// api.mjs: two ways an API can validate a bearer token
import { jwtVerify } from 'jose';
import { publicKey } from './auth-server.mjs';

// 1. Self-contained JWT: verify the signature and claims locally, no network call
export async function validateJwt(token) {
  try {
    const { payload } = await jwtVerify(token, publicKey, {
      algorithms: ['ES256'], issuer: 'https://auth.example.com', audience: 'https://api.example.com', typ: 'at+jwt' });
    return { ok: true, sub: payload.sub, scope: payload.scope };
  } catch (e) { return { ok: false, error: e.code }; }
}

// 2. Opaque token: ask the authorization server (RFC 7662) on every call
export async function validateOpaque(token, introspectUrl) {
  const r = await fetch(introspectUrl, { method: 'POST',
    headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token }) });
  const data = await r.json();
  return data.active ? { ok: true, sub: data.sub, scope: data.scope } : { ok: false, error: 'inactive' };
}

The local check pins the algorithm and checks issuer, audience, token type and expiry. Skipping any one of those is how most JWT vulnerabilities happen. The introspection call sends the token to the authorization server, which answers {"active": true, ...} or {"active": false}.

How do you revoke a token?

Revoke an opaque token at the authorization server and it stops working on the next call; a JWT keeps working until it expires unless the API also checks a denylist. That difference is the main reason to choose one format over the other.

For JWTs, you have three options:

  • Keep access tokens short, 5 to 15 minutes, and revoke the refresh token. The damage window is one token lifetime.
  • Denylist the token's jti until its expiry, and check the list on each call.
  • Introspect high-risk calls only, such as payments and exports, and verify the rest locally.

RFC 7009 defines a standard revocation endpoint, so clients can revoke their own tokens at sign-out.

How do refresh tokens work, and why rotate them?

A refresh token lets a client get a new access token without the user signing in again; rotation means each refresh token works once and is replaced by a new one. If an old refresh token is ever used again, someone has copied it, so the server cancels the whole chain.

This is called refresh token rotation with reuse detection. The OAuth 2.0 Security Best Current Practice (RFC 9700) requires refresh tokens for public clients, such as browser and mobile apps, to be either sender-constrained or rotated. Here's the logic from our test authorization server:

Node.js · auth-server.mjs (refresh rotation)
// Refresh token rotation with reuse detection: a used refresh token kills its whole family
export async function useRefresh(token) {
  const r = refresh.get(token);
  if (!r || revokedFamilies.has(r.family)) return { error: 'invalid_grant' };
  if (r.used) { revokedFamilies.add(r.family); return { error: 'invalid_grant', reuse_detected: true }; }
  r.used = true;
  return issue(r.sub, r.scope, { format: r.format, family: r.family });
}

Every refresh token belongs to a family that starts at sign-in. Using one marks it as used and returns a new pair in the same family. Replaying a used one revokes the family, which also locks out the legitimate client. That's intentional: the user signs in again, and the attacker's copy is dead.

What happened when we tested token validation, revocation and refresh?

We ran an authorization server, both validation methods and the refresh logic with Node.js 18+ and jose 5.9.6. Every result matched the behaviour described above:

Token validation, revocation and refresh test results

TestResult
Opaque token, validated by introspectionValid
Same opaque token after revocationRejected on the next call: active: false
JWT, validated locallyValid
Same JWT after the server "revoked" itStill accepted until it expires
JWT with a tampered signatureRejected: ERR_JWS_SIGNATURE_VERIFICATION_FAILED
Average validation time, 2,000 calls eachJWT locally: 0.10 ms. Opaque via introspection over loopback HTTP: 1.9 ms
Use a refresh token onceNew access token and a new, different refresh token
Replay the old refresh tokenRejected, reuse detected, token family revoked
Legitimate client uses its newest refresh tokenRejected: the user must sign in again

Swipe sideways to see all columns →

Token-based authentication test results comparing opaque tokens and JWTs on revocation and validation time, and showing refresh token rotation detecting a replayed refresh token and revoking the token family

The latency numbers come from one laptop with the authorization server on the same machine. Across a real network, introspection adds a round trip, often several milliseconds. That's why many teams verify JWTs locally for everyday calls and introspect, or use opaque tokens, for the calls where instant revocation matters most.

What are the pros and cons of token-based authentication?

Token-based authentication scales across services, clients and partners and never sends passwords to APIs, but tokens work for whoever holds them and self-contained tokens are hard to revoke. The pros win for APIs; the cons are manageable with short lifetimes and good storage.

Pros:

  • No passwords on every call. Credentials are sent once, to the authorization server.
  • Works for every kind of client: browsers, mobile apps, back-end services, partners and AI agents.
  • Scales without shared session storage. JWTs verify anywhere with the issuer's public key.
  • Carries permissions. Scopes and claims limit what each token can do. See OAuth scopes.
  • Expires on its own. A short lifetime caps the damage of a leak.

Cons:

  • Bearer tokens work for whoever holds them, unless they're bound to a key with mTLS or DPoP.
  • JWTs are hard to revoke before they expire.
  • Token storage in browsers is risky; scripts can read tokens in localStorage.
  • Tokens leak in places passwords don't, such as logs, URLs, screenshots and code repositories.
  • More moving parts: an authorization server, keys, rotation and refresh logic.

When should you use token-based authentication?

Use token-based authentication for any API that's called by more than one client, by other services, by partners or by AI agents. Use sessions for a single server-rendered web app, and keep API keys for identifying applications on low-risk APIs.

Token-based authentication is right for you if

  • Your API is called by mobile apps, single-page apps, services, partners or AI agents.
  • Requests cross domains or pass through several services or gateways.
  • You need scoped, delegated access, such as "this app may read my orders".
  • You want access to expire and refresh without asking for passwords again.

Sessions or API keys may be enough if

  • You run one server-rendered web app on one domain: use sessions.
  • You only need to identify which application is calling a low-risk API: an API key may do.
  • You can't run or rent an authorization server yet. Plan the move, because partner and agent access will need tokens.

Token-based authentication best practices

The most important token-based authentication best practices are short lifetimes, strict validation, safe storage, rotation and the ability to revoke. These apply whether your tokens are JWTs or opaque strings.

  1. Send tokens only over HTTPS, and only in the Authorization header. Never put tokens in URLs or query strings, where they end up in logs and browser history.
  2. Keep access tokens short-lived: 5 to 15 minutes for user-facing apps, up to an hour for machine-to-machine.
  3. Validate everything: signature with a pinned algorithm, issuer, audience, expiry and token type. Never trust a token you've only decoded.
  4. Scope every token to the API and operations it needs. A token for the orders API must fail on the billing API.
  5. Rotate refresh tokens and detect reuse, as RFC 9700 requires for public clients.
  6. Keep tokens out of browser JavaScript. Use a backend-for-frontend with HttpOnly, Secure, SameSite cookies, not localStorage.
  7. Use PKCE for every authorization code flow, and never the implicit flow, which OAuth 2.1 removes.
  8. Bind high-value tokens to the client with mTLS (RFC 8705) or DPoP (RFC 9449), so a stolen token is useless alone.
  9. Make revocation possible: opaque tokens or introspection for high-risk APIs, a jti denylist or short lifetimes for JWTs.
  10. Scan code and logs for leaked tokens, and rotate anything that leaks immediately.
  11. Give each AI agent its own short-lived, narrowly scoped token, and use token exchange (RFC 8693) when it acts for a user. See securing MCP endpoints.

These are the token side of the principle of least privilege: every token should allow as little as possible, for as short a time as possible.

Where should tokens be validated: API gateway or service?

Validate tokens at the API gateway so every API applies the same rules, and keep a light check in each service for calls that don't come through the gateway. Gateway validation removes duplicate code and gives you one place to change algorithms, audiences and introspection settings.

The hard part comes with several gateways. Each one validates tokens with its own plugin and settings, so one gateway checks the audience and another doesn't. The DigitalAPI API Gateway applies the same token validation, scope and introspection policy across the gateways you already run. Teams using the DigitalAPI API Developer Portal give partners self-service credentials with the right scopes and lifetimes from day one.

See how DigitalAPI applies one token policy across every gateway you run → Book a Demo

Key takeaways

  • Token-based authentication replaces passwords and sessions on each request with a token the API can check.
  • Know your tokens: access tokens go to APIs, refresh tokens to the authorization server, ID tokens to apps.
  • JWTs validate fast and locally but revoke slowly; opaque tokens revoke instantly but need introspection.
  • Rotate refresh tokens with reuse detection, and keep access tokens to minutes.
  • Keep tokens out of URLs, logs and browser JavaScript, and bind high-value tokens to the client.

Frequently asked questions

1. What is token-based authentication?

Token-based authentication is a method where a client proves its identity by sending a token with each request instead of a password or session cookie. An authorization server issues the token after the client signs in, and the API validates it by checking its signature or asking the issuer. Tokens expire and can be refreshed or revoked.

2. What is an example of token-based authentication?

A partner app sends its client ID and secret to an authorization server and receives an access token valid for 10 minutes. It then calls GET /orders with the header Authorization: Bearer <token>. The API verifies the token, checks it carries the orders:read scope, and returns the orders.

3. What is the difference between token and session authentication?

Session authentication stores the user's state on the server and gives the browser a session ID cookie. Token authentication gives the client a token that carries, or points to, the identity and permissions the API needs. Sessions suit one web app on one domain; tokens suit APIs called by many apps, services, partners and agents.

4. Is JWT the same as token-based authentication?

No. Token-based authentication is the overall method. A JWT is one token format that carries signed claims the API can verify locally. Token-based authentication can also use opaque tokens, which are random strings the API checks with the issuer through introspection.

5. What is an opaque token?

An opaque token is a random string with no readable content. The API can't verify it on its own, so it asks the authorization server whether the token is active through token introspection (RFC 7662). Opaque tokens can be revoked instantly and reveal nothing to the client, at the cost of a network call per check.

6. What is the difference between an access token and a refresh token?

An access token is short-lived, often minutes, and is sent to the API on every call. A refresh token lives longer, is sent only to the authorization server, and is used to get new access tokens without signing in again. Refresh tokens are more valuable to attackers, so they should be rotated and guarded closely.

7. Where should I store tokens in a web app?

Don't store tokens in localStorage or sessionStorage, because any script running on the page can read them. The safest pattern is a backend-for-frontend that keeps tokens on the server and gives the browser an HttpOnly, Secure, SameSite session cookie. Mobile apps should use the platform keychain or keystore.

8. How do you revoke a token?

Opaque tokens are revoked at the authorization server and stop working on the next introspection call. JWTs stay valid until they expire, so keep them short-lived, revoke the refresh token, and add a denylist of revoked token IDs (jti) for high-risk APIs. RFC 7009 defines a standard revocation endpoint.

9. Is token-based authentication secure?

Token-based authentication is secure when tokens are short-lived, sent only over HTTPS, validated strictly, scoped narrowly and stored out of reach of scripts. The main risk is that bearer tokens work for whoever holds them, so leaked tokens must expire within minutes or be bound to the client with mTLS or DPoP.

10. Is OAuth the same as token-based authentication?

No. OAuth 2.0 is an authorization framework that defines how clients get access tokens from an authorization server. Token-based authentication is the broader pattern of presenting a token instead of credentials. OAuth is the most common way to issue the tokens, and OpenID Connect adds the sign-in layer on top.

Conclusion

Token-based authentication is how almost every modern API knows who's calling: one sign-in, then a token on every request. It works for browsers, mobile apps, services, partners and AI agents in a way sessions and passwords never could.

The format matters less than the discipline around it. Keep access tokens short, validate them strictly, rotate refresh tokens, store tokens out of reach of scripts, and make sure you can revoke them. For how tokens fit with keys, roles and the rest of API security, read our guide to API authentication and the difference between authentication and authorization.


How safely do you grant API access to partners and AI agents? Get your free readiness score: Check Your API Access Readiness

Prefer a walkthrough?
Book a Demo
About the author
Dhayalan Subramanian

Dhayalan Subramanian is Associate Director, Product Growth at DigitalAPI, where he leads go-to-market and product growth for the company’s multi-gateway API management platform. His work focuses on helping large enterprises and mid-market cloud companies consolidate APIs across AWS, Azure, Apigee, Kong, MuleSoft, and other gateways into a single control plane for governance, discovery, monetization, and agent consumption.

‍

Dhayalan brings 14+ years of experience across product strategy, enterprise architecture, and engineering leadership. Earlier in his career, he held senior roles at Encora (as Associate Architect and Technical Manager), Mindtree (Technology Lead), Tech Mahindra (Technical Lead), and Primus Analytics, where he designed integration frameworks and delivered enterprise-grade digital platforms for global customers.

‍

At DigitalAPI, he works directly with platform, integration, and developer experience leaders at Fortune 500 organizations to operationalize unified API catalogs, developer portals, and MCP-ready APIs. He writes regularly on API developer experience, API governance, and AI agent architectures.

Become AI-ready
Make every API agent-callable.
An 8-week pilot. We connect to your gateways, ship MCP-callable APIs, and onboard your first agent.
0 rip-and-replace
Same auth, same audit
Live in production in 8 weeks
Get started

One email a fortnight. Worth opening.

A short digest of what we're writing, what we're learning from customers, and the handful of links you'd actually want from us. No tracking pixels.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.