What is Token Authentication?
Token-based authentication is a secure, stateless protocol where a server verifies user credentials (like username/password) once and issues a unique, encrypted token. The client stores this token and sends it with subsequent requests to access protected resources, eliminating the need to resend credentials. It is useful for API security, mobile apps, and single-sign-on (SSO) systems.
Key aspects of token authentication:
- Workflow: User logs in → Server verifies → Server generates and sends signed token → Client stores token (local storage/cookie) → Client sends token with each API request.
- Statelessness: Unlike session-based authentication, the server does not need to store session data. The token itself contains all necessary user information, improving scalability.
- Token types: Commonly uses JSON Web Tokens (JWT).
- Security: Tokens are temporary, can have expiration times, and are designed to prevent unauthorized access.
- Revocation: Tokens can be invalidated when a user logs out.
This is part of a series of articles about API security.
In this article:
Workflow
The workflow begins when a user submits credentials to an authentication endpoint. If valid, the server generates a token, often a JSON web token (JWT) or opaque token, and returns it to the client. The client stores the token, usually in memory or local storage, and includes it in the Authorization header of subsequent requests to protected resources. The server validates the token on each request, checking its integrity and claims before granting access.
This workflow separates authentication from resource access. The login endpoint verifies identity and issues tokens, while resource servers validate the token's signature and claims. This separation supports modular systems where authentication and authorization logic are managed independently. Any stateless server instance can validate tokens without shared session storage.
2. Statelessness
Token authentication is stateless, meaning the server does not retain information about authenticated clients between requests. Each request carries the required authentication information within the token, typically encoded and signed to prevent tampering. The server decodes and validates the token to confirm identity and permissions, without referencing external session stores.
Statelessness allows servers to be added or removed without session replication or affinity concerns. Load balancers can route requests to any server instance. Token invalidation and revocation require additional mechanisms, since the server cannot delete a session to log a user out.
Token Types
Two main categories of tokens are used in authentication: opaque tokens and self-contained tokens. Opaque tokens are random strings with no intrinsic meaning; their contents are known only to the authorization server, which maintains a mapping in a backend database. Self-contained tokens, such as JWTs, encode user claims, expiration time, and metadata within the token and are cryptographically signed to ensure integrity.
Opaque tokens allow direct revocation by removing them from the database. Self-contained tokens reduce server-side lookups and are easier to validate in distributed environments but are harder to revoke before expiration. The choice depends on security requirements, infrastructure, and control over the token lifecycle.
Security
Tokens must be transmitted over HTTPS to prevent interception. In self-contained formats like JWT, token contents should be signed and, when necessary, encrypted to prevent tampering and unauthorized access to sensitive information. Strong cryptographic algorithms are required to ensure token integrity.
Security considerations include token expiration and scope limitation. Tokens should have short validity periods to reduce risk if compromised. Refresh tokens must be protected and rotated regularly. Proper audience and issuer checks, along with monitoring token usage patterns, help detect misuse and prevent unauthorized access.
Revocation
Revocation is a challenge, particularly for self-contained tokens. Once issued, a token cannot be revoked until it expires unless a revocation mechanism exists. Opaque tokens can be revoked by removing their mapping from a database.
For JWTs and other self-contained tokens, revocation may require denylists or lists of revoked tokens. Another approach is to use short-lived access tokens with rotating refresh tokens. Implement logout and revocation endpoints and ensure clients handle token expiration properly.
Connected
Connected tokens require a direct physical or logical connection to the device or system they authenticate. Examples include USB security keys, smart cards, and hardware tokens plugged into a computer or terminal. These tokens use cryptographic operations, such as signing a challenge with a private key stored on the device.
They are used in high-security environments such as government systems or enterprise networks. The physical presence requirement reduces remote attacks but can create deployment challenges. Integration may require hardware readers and drivers, and lost tokens require replacement procedures.
Contactless
Contactless tokens authenticate users wirelessly using technologies such as near field communication (NFC) or Bluetooth low energy (BLE). Examples include NFC-enabled access cards and smartphones configured as digital keys.
They are used for access control, payments, and mobile authentication. Contactless tokens can be susceptible to proximity-based attacks, such as relay attacks or eavesdropping if not secured. Mitigations include mutual authentication, cryptographic challenge-response protocols, and limiting wireless range.
Disconnected
Disconnected tokens operate independently from the system they authenticate and do not require a direct connection. Examples include hardware one-time password (OTP) tokens and mobile apps that generate time-based codes used in two-factor authentication (2FA). The user reads the code and enters it into the authentication interface.
These tokens are not susceptible to malware on the host device or network-based interception. They rely on user entry of codes. Time-based tokens require clock synchronization, and physical tokens can be lost or damaged.
Uri Dorot
Uri Dorot is a senior product marketing manager at Radware, specializing in application protection solutions, service and trends. With a deep understanding of the cyberthreat landscape, Uri helps bridge the gap between complex cybersecurity concepts and real-world outcomes.
Tips from the Expert:
In my experience, here are tips that can help you implement token authentication with fewer hidden failure modes and a smaller blast radius:
1. Prefer opaque access tokens at the edge, JWTs only where you truly need self-containment:
Use opaque tokens for public/partner APIs so you can revoke instantly and do fine-grained risk scoring; reserve JWTs for internal service-to-service where latency and offline verification matter most.
2. Adopt “two-token classes” with different threat models:
Separate tokens used in browsers (high XSS/CSRF risk) from tokens used by backend services (higher trust, lower user-driven injection). Different lifetimes, scopes, audience rules, and storage patterns reduce cross-context leakage.
3. Make scope design hierarchical and non-composable by default:
Avoid scopes that accidentally combine into admin-equivalent power. Design scopes so “read + write” doesn’t implicitly unlock “manage,” and explicitly forbid wildcard scopes for third parties.
4. Build revocation around events, not lists:
Instead of denylisting individual tokens, track revocation “epochs” per user/device/tenant and reject tokens issued before the latest epoch. This scales better and makes “logout everywhere” and incident response fast.
5. Add token misuse detection as a first-class auth feature:
Track per token/client: geo/ASN churn, impossible travel, concurrency spikes, and endpoint-mix shifts. Most real compromises look like “valid auth with weird behavior,” and analytics beats cryptography here.
Token-based and cookie-based authentication differ in session management and scalability.
Cookie-based authentication relies on the server maintaining session state, storing session data in memory or a database and identifying users with a session ID sent via browser cookies. Cookie-based authentication is integrated with browsers and traditional web applications, with built-in support for session management and CSRF protection, but cross-origin access and API integration are more complex.
Token-based authentication is stateless; the server issues a signed token that the client presents with each request. The server validates the token without referencing stored session information. Token-based authentication is used for APIs, single-page applications, and distributed systems that require horizontal scalability. Requests can be handled by any server instance.
Public APIs and Partner Ecosystems
Token authentication secures public APIs and partner integrations. API consumers authenticate with an authorization server, receive a token, and present it to access endpoints. This model supports fine-grained access control, rate limiting, and usage monitoring.
Organizations can expose APIs while controlling access conditions. It integrates with API gateways, monitoring tools, and developer portals. The stateless nature of tokens supports large request volumes without session management overhead.
Enterprise SSO and Workforce Access
Enterprises implement token authentication as part of single sign-on (SSO) solutions. Employees authenticate with an identity provider, which issues a token used to access multiple applications and services. This reduces repeated logins and centralizes authentication policy enforcement.
Token-based SSO supports protocols such as OAuth 2.0 and OpenID Connect, enabling integration with cloud services, internal apps, and third-party vendors. It allows multi-factor authentication and conditional access policies at the identity provider level. Centralized token management supports revocation and auditing.
IoT and Constrained Devices
Token authentication is used in internet of things (IoT) scenarios where devices have limited processing power and memory. Devices use lightweight tokens, such as JSON web tokens or reference tokens, to authenticate with cloud services or APIs.
Tokens reduce the need for persistent connections and stateful sessions. They can be issued with specified scopes, lifetimes, and audience restrictions. Tokens are provisioned during device onboarding and refreshed periodically.
Mobile and Desktop Native Applications
Native applications on mobile and desktop platforms use token authentication to interact with backend APIs. After initial login, often via a browser-based authorization flow, the app receives access and refresh tokens to authenticate subsequent requests without re-entering credentials.
Tokens are stored securely on the device, such as in a secure keychain or keystore, and can be refreshed when they expire. Avoiding direct handling of credentials within the app reduces the risk of credential theft.
Token authentication provides a stateless method for securing APIs and applications but introduces additional considerations.
Pros
- Scalability: Works in distributed and horizontally scaled systems. Any server can process requests without shared session state.
- Decoupling: Authentication and resource servers can operate independently.
- Cross-platform support: Tokens are language-agnostic and usable across mobile, desktop, and browser-based clients.
- Security mechanisms: Supports short-lived access tokens, scopes, and refresh tokens.
- Integration: Works with APIs and protocols such as OAuth 2.0 and OpenID Connect.
- Reduced server load: Servers do not manage sessions.
Cons
- Token revocation complexity: Self-contained tokens such as JWTs cannot be revoked easily before expiration without additional infrastructure.
- Exposure risk: Tokens are bearer credentials and can be used if intercepted. HTTPS and secure storage are required.
- Short token lifetimes require management: Expiration and refresh strategies require coordination.
- Limited built-in CSRF protection: Requires explicit anti-CSRF measures.
- Client-side storage risks: Storing tokens in local storage can expose them to XSS attacks.
- Overhead of token validation: Complex claims can add CPU overhead.
Related content: Read our guide to JWT authentication.
Here are some important practices to consider when implementing a token-based authentication system.
1. Use Short-Lived Access Tokens with Rotating Refresh Tokens
Access tokens should have short expiration times, often a few minutes. They are commonly combined with refresh tokens, which are long-lived credentials used to obtain new access tokens without requiring the user to log in again.
Implement refresh token rotation. Each time a refresh token is used, issue a new one and invalidate the old one. If a reused refresh token is detected, revoke access. Store refresh tokens securely and assign limited scope and lifetime. Bind them to a specific client or device when possible.
2. Implement Automated Key Rotation and Pin Trusted JWKS Sources
Cryptographic keys used to sign and verify tokens should be rotated regularly. Implement automated key rotation to generate, distribute, and retire keys on a defined schedule. For systems using JWTs, expose public keys through a JWKS (JSON web key set) endpoint. Resource servers fetch and cache keys for verification.
Pin the JWKS source using domain validation or secure provisioning to ensure only trusted keys are accepted. Automated key management supports incident response. If a key is compromised, revoke it and issue tokens signed with a new key.
3. Prefer Sender-Constrained Tokens for High-Value Operations
Bearer tokens can be used by anyone who possesses them. For high-value operations, use sender-constrained tokens that bind the token to a client or cryptographic key.
One method is mutual TLS (mTLS), where the client presents a certificate during TLS negotiation. Another is proof-of-possession (PoP), where the client signs parts of the request using a private key associated with the token. These approaches reduce replay and token theft risks.
4. Keep Claims Minimal
Include only the information required for authorization decisions. Common claims include subject (sub), issuer (iss), expiration (exp), audience (aud), and roles or scopes. Avoid embedding unnecessary details such as full user profiles or sensitive metadata.
Large tokens increase network overhead and validation cost. When additional data is required, use lightweight tokens that reference external user data stored securely.
5. Prevent Token Leakage in Logs, Crash Reports, and Referrers
Tokens must be treated as sensitive secrets. If a token is logged or transmitted in an unsafe context, it can be intercepted and reused by attackers. Never include tokens in URLs, as these are often logged by servers, proxies, and analytics tools. Tokens in URLs may also be leaked via the Referer header when navigating between sites.
Ensure that the application sanitizes all logs, crash reports, and monitoring output. Avoid printing tokens to the console, log files, or third-party observability tools. Use structured logging to redact sensitive fields automatically, and implement token-aware error handling to suppress or scrub debug information.
Token authentication enables scalable, stateless access control for modern APIs and distributed applications. However, misconfigurations, token leakage, and automated abuse can expose authentication workflows to replay attacks, credential stuffing, and unauthorized access attempts. Radware helps organizations secure token-based authentication systems by combining continuous API discovery, behavioral analysis, and runtime enforcement that detect anomalies, block exploitation attempts, and maintain consistent protection across API-driven environments.
Radware API Security continuously discovers and inventories APIs, helping organizations identify endpoints that rely on token-based authentication across environments. Behavioral analytics establish baselines for normal token usage and detect anomalies such as replay activity, unusual access sequences, or unauthorized function calls. Centralized visibility highlights authentication patterns and potential misuse across distributed services. These insights help teams identify risks associated with token exposure or improper validation.
Radware Application Protection Service protects token-based APIs through real-time traffic inspection and ML-driven behavioral analysis. Runtime enforcement detects malformed authentication requests, suspicious token usage patterns, and attempts to bypass authorization controls. Integrated protections help mitigate OWASP API risks while maintaining consistent security across hybrid and cloud-native environments. This ensures token authentication workflows remain protected even as application architectures evolve.
Radware Cloud WAF Service mitigates threats targeting authentication endpoints by blocking malicious payloads and abnormal request patterns before they reach backend services. Virtual patching helps reduce exposure when token validation weaknesses are discovered but cannot be immediately remediated. Adaptive protections also help enforce request validation and reduce risks tied to misconfigured authentication flows. Real-time monitoring improves visibility into authentication abuse patterns.
Radware Bot Manager mitigates automated attacks targeting token-based authentication, including credential stuffing, token harvesting, and brute-force login attempts. Advanced detection distinguishes legitimate automation from malicious actors attempting to exploit authentication workflows. Reducing automated abuse limits large-scale exploitation of token-based systems. Continuous monitoring also provides insight into emerging attack patterns.