Bearer Tokens Explained
A practical guide to bearer tokens, including the Authorization header, JWTs, access tokens, expiration, token storage, validation, security risks, and common implementation mistakes.
Bearer tokens are one of the most common ways to authenticate requests to modern web APIs. They are frequently sent in the HTTP Authorization header and allow a client to prove that it possesses a credential accepted by the server.
The basic syntax is simple: the client sends the word Bearer followed by a token. The server extracts the token, validates it according to the authentication system, and then decides whether the request can proceed.
Bearer tokens are often associated with JSON Web Tokens, or JWTs, but the two concepts are not the same. Bearer describes how a credential is presented and used, while JWT describes one possible token format. Understanding this distinction helps avoid confusion when designing or debugging API authentication.
What Is a Bearer Token?
A bearer token is a credential that grants access to a protected resource to whoever successfully presents it. The term bearer reflects an important property: the server generally does not require the client to prove ownership of the token through a separate cryptographic mechanism. Possession of the valid token is enough for the server to process it according to its permissions.
Bearer tokens are commonly sent using the HTTP Authorization header.
GET /api/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...The token itself can have many different formats. It could be a JWT, an opaque random string, or another credential format supported by the authentication system.
How Bearer Authentication Works
A typical bearer-token flow starts when a client authenticates through an authentication service. After successful authentication, the client receives an access token.
Client
|
| Authenticate
v
Authentication Server
|
| Access token
v
Client
|
| Authorization: Bearer <token>
v
API
|
| Validate token
v
Protected ResourceThe client then includes the access token with requests to protected endpoints. The API validates the token and determines the identity and permissions associated with it.
The Authorization Header
The standard HTTP Authorization header is commonly used to transport bearer credentials.
Authorization: Bearer <token>Bearer is the authentication scheme. The token follows it as the credential value.
GET /api/orders
Host: api.example.com
Authorization: Bearer abc123The exact token value and validation process depend on the API. Clients should normally treat the token as opaque and should not make assumptions about its internal structure unless the API documentation explicitly requires them.
Bearer Tokens and JWTs Are Not the Same
A common misconception is that bearer token means JWT. A bearer token is a credential used according to the bearer authentication scheme. JWT is a standardized token format.
| Concept | Meaning |
|---|---|
| Bearer token | A credential presented by the client as proof of possession |
| JWT | A token format containing encoded claims and a cryptographic signature or MAC |
| Access token | A credential used to access a protected resource |
| API key | A credential commonly used to identify or authenticate an API client |
A JWT can be used as a bearer token, but an opaque random string can also be used as a bearer token.
What Does Bearer Mean?
Bearer means that the party presenting the credential is treated as the bearer of that credential. The API does not necessarily know whether the person or application presenting it is the original recipient.
This makes bearer tokens convenient but also makes them sensitive. If an attacker obtains a valid bearer token, the attacker may be able to use it until it expires, is revoked, or otherwise becomes invalid.
Bearer Tokens in OAuth 2.0
Bearer tokens are strongly associated with OAuth 2.0 access tokens. OAuth 2.0 defines an authorization framework in which a client can obtain an access token and use it to access a protected resource.
The client commonly presents an OAuth access token using the Authorization header.
GET /resource
Host: api.example.com
Authorization: Bearer mF_9.B5f-4.1JqMThe resource server validates the access token according to the authorization system. The token can be opaque or structured, depending on the implementation.
Access Tokens
An access token is a credential that allows a client to access protected resources within a defined scope or permission set. OAuth 2.0 access tokens are commonly presented as bearer tokens.
An access token should be limited to the resources and operations that the client actually needs. The authorization server and resource server determine the exact semantics.
Opaque Bearer Tokens
An opaque token is a value whose internal contents have no meaning to the client. It might look like a random string.
Authorization: Bearer 8f7a3c0d2e9b4a1f...The server can look up the token in a database, cache, or authorization service to determine whether it is valid and what identity or permissions it represents.
Opaque tokens make it possible to keep token state on the server. They also allow the server to revoke a token by removing or invalidating its server-side record.
JWT Bearer Tokens
A JWT can also be used as a bearer token. Unlike an opaque token, a JWT contains encoded claims that can be inspected by a recipient. Its signature allows the recipient to verify that the token was produced by a trusted issuer and has not been modified.
GET /api/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...The server should still validate the token rather than merely decoding it. A decoded payload is not proof that the token is authentic.
JWT Structure
A typical JWT consists of three Base64URL-encoded sections separated by periods.
header.payload.signatureThe header commonly contains the token type and signing algorithm. The payload contains claims. The signature protects the signed data against unauthorized modification when validated correctly.
{
"alg": "HS256",
"typ": "JWT"
}Common JWT Claims
JWT claims provide information about the token or the identity and context it represents. Some registered claims have standardized meanings.
| Claim | Typical meaning |
|---|---|
| iss | Issuer of the token |
| sub | Subject represented by the token |
| aud | Intended audience |
| exp | Expiration time |
| nbf | Not valid before time |
| iat | Issued-at time |
| jti | Token identifier |
Applications can also use private claims, but they should define their meaning clearly and avoid placing unnecessary sensitive information in a bearer token.
Bearer Tokens and Authentication
A bearer token can serve as an authentication credential because the server can use it to establish which identity is making a request. However, the token may also carry or reference authorization information.
The distinction between authentication and authorization remains important. A valid bearer token can identify the caller without necessarily granting permission to every endpoint.
Valid token
|
v
Identity established
|
v
Permission check
|
v
Access granted or deniedBearer Tokens and Authorization
Authorization determines what the bearer of the token can do. A token may be associated with scopes, roles, permissions, or another access-control model.
{
"sub": "user-123",
"scope": "orders:read orders:create"
}The API can use these values as part of its authorization policy. A token with orders:read should not automatically be assumed to have permission to delete orders.
Bearer Tokens and HTTPS
Bearer tokens should be transmitted over HTTPS. Because possession of a valid bearer token can be sufficient to access a protected API, exposing the token over an unencrypted connection can allow an attacker to intercept and reuse it.
Where Should Bearer Tokens Be Stored?
Token storage depends on the type of application and authentication architecture. Browser applications require particular care because JavaScript-accessible storage can become exposed if an attacker successfully executes malicious script in the application's origin.
For browser-based applications, an architecture using secure, HttpOnly cookies can reduce direct JavaScript access to session credentials. Other architectures use short-lived access tokens with carefully designed storage and refresh mechanisms.
There is no single storage mechanism that is automatically correct for every application. The design should account for the application's threat model, browser behavior, CSRF protections, XSS risks, and session architecture.
Bearer Tokens in localStorage
A common browser implementation stores an access token in localStorage and reads it when making API requests. This is convenient, but JavaScript running in the page can access localStorage.
If an application has an exploitable cross-site scripting vulnerability, malicious script may be able to read a token stored there. This is one reason token storage should be considered together with the application's XSS defenses and overall authentication architecture.
Bearer Tokens in Cookies
An authentication credential can also be associated with a cookie. HttpOnly prevents JavaScript from reading the cookie directly, while Secure instructs browsers to send it only over secure connections.
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=LaxCookies introduce their own security considerations, including cross-site request forgery. SameSite settings and appropriate CSRF defenses should be considered when cookies are used for authentication.
Bearer Token Expiration
Access tokens should have a defined lifetime appropriate to the application. Short-lived credentials can reduce the period during which a stolen token remains useful.
For JWTs, expiration is commonly represented by the exp claim. An API must validate that the token has not expired before accepting it.
{
"sub": "user-123",
"iat": 1790000000,
"exp": 1790003600
}The exact lifetime should be determined by the application's security requirements rather than choosing an arbitrary duration that applies to every system.
Refresh Tokens
Applications that use short-lived access tokens may also use refresh tokens. A refresh token can be exchanged for a new access token according to the authentication system's rules.
Refresh tokens are different from ordinary bearer access tokens in their intended purpose and lifecycle. They should receive strong protection and should not automatically be sent to every API request.
Revoking Bearer Tokens
Token revocation determines how a previously issued credential can be invalidated before its normal expiration.
Opaque tokens can be revoked by changing or removing the corresponding server-side record. Self-contained JWT access tokens are more difficult to revoke immediately because a resource server may be able to validate them without consulting a central token store.
Systems that require immediate invalidation may use short token lifetimes, server-side state, token identifiers, revocation lists, or other architecture-specific mechanisms.
Validating a Bearer Token
The API should validate every bearer credential according to the authentication system that issued it. For an opaque token, this can involve checking a server-side token store. For a JWT, it can involve cryptographic signature verification and claim validation.
Typical JWT validation can include the signature, expected algorithm, issuer, audience, expiration, not-before time, and other application-specific requirements.
Receive token
|
v
Validate structure
|
v
Verify signature
|
v
Validate issuer and audience
|
v
Validate expiration
|
v
Evaluate permissionsDo Not Only Decode a JWT
JWT payloads are easy to decode, but decoding is not the same as validation. Anyone who possesses a JWT can generally decode its Base64URL-encoded header and payload.
An API must verify the cryptographic properties and required claims before trusting the information. Otherwise, an attacker could potentially construct or modify a token and have the application accept untrusted claims.
JWT Algorithms
JWTs can use different signing algorithms, including symmetric algorithms such as HMAC and asymmetric algorithms such as RSA or elliptic-curve based algorithms.
The resource server should know which algorithms and keys are expected for a particular token type or issuer. Applications should not blindly accept whatever algorithm value appears in an untrusted token header.
Bearer Tokens and API Keys
API keys and bearer tokens can look similar because both can be sent as HTTP credentials. However, they can serve different purposes and have different lifecycle and authorization models.
Authorization: Bearer <access-token>X-API-Key: <api-key>The header syntax alone does not determine the security properties of a credential. The server-side authentication and authorization system defines what the credential means.
Bearer Tokens and Basic Authentication
HTTP Basic Authentication sends a username and password-derived credential using the Basic authentication scheme. Bearer authentication instead sends a bearer credential using the Bearer scheme.
| Scheme | Typical credential |
|---|---|
| Basic | Username and password credentials |
| Bearer | Access token or another bearer credential |
Both should be protected with HTTPS in production. Bearer authentication is especially common for APIs where the client obtains a token separately and then presents it on subsequent requests.
Bearer Tokens and 401 Responses
When a protected API cannot authenticate a request, it can return HTTP 401 Unauthorized. This can happen when the Authorization header is missing, the token is malformed, expired, or otherwise invalid.
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": "invalid_token"
}A valid token does not necessarily grant permission to every resource. If the identity is authenticated but lacks the required permission, the API may return 403 Forbidden according to its authorization policy.
The WWW-Authenticate Header
HTTP authentication challenges can be communicated with the WWW-Authenticate response header. For bearer authentication, an API can provide information about the authentication challenge and, where appropriate, an error condition.
HTTP/1.1 401 Unauthorized
WWW-Authenticate: BearerMore detailed challenges can include parameters such as an error or error description, depending on the protocol and server implementation.
Token Leakage Risks
Because bearer tokens can be used by whoever possesses them, accidental exposure is a serious risk. Tokens should not be unnecessarily written to application logs, analytics events, URLs, screenshots, public repositories, or error messages.
- Do not place access tokens in URLs when a header can be used.
- Do not commit tokens to source control.
- Avoid logging complete Authorization headers.
- Do not include tokens in analytics events.
- Protect tokens in browser storage according to the application's threat model.
- Use HTTPS for token transmission.
- Rotate or revoke exposed credentials when possible.
Why Tokens Should Not Be Put in URLs
URLs can be stored in browser history, server logs, proxy logs, analytics systems, and referrer-related contexts. Putting a bearer token into a URL therefore creates additional opportunities for accidental disclosure.
GET /api/profile?access_token=secret-tokenToken Lifetime and Security
A bearer token's lifetime represents an important trade-off. A very long-lived token can remain useful for a long period if compromised, while an extremely short-lived token may require frequent renewal and increase implementation complexity.
Access-token lifetime should therefore be designed together with refresh behavior, revocation requirements, user experience, and the sensitivity of the protected resources.
Audience and Issuer Validation
For JWT bearer tokens, validating the issuer and audience can prevent a token intended for one service or API from being accepted by another service that should not trust it.
{
"iss": "https://auth.example.com",
"aud": "orders-api"
}The expected issuer and audience should be defined by the application. A token with a valid signature is not necessarily valid for every resource server.
Bearer Tokens in Frontend Applications
A frontend application often obtains an access token and adds it to API requests through an HTTP client or request wrapper.
const response = await fetch("/api/profile", {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});The frontend should not assume that the presence of a token means every API operation is available. The server remains responsible for enforcing authorization.
Bearer Tokens in Backend Services
Backend services can also use bearer tokens when communicating with another API. The calling service obtains or receives a credential and includes it in the Authorization header.
const response = await fetch("https://api.example.com/orders", {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});Server-side applications should keep credentials outside source code and use appropriate secret-management mechanisms for the deployment environment.
Common Bearer Token Mistakes
- Assuming every bearer token is a JWT.
- Trusting decoded JWT claims without validating the signature.
- Accepting arbitrary JWT algorithms.
- Failing to validate token expiration.
- Skipping issuer or audience validation when required.
- Sending tokens over unencrypted HTTP.
- Putting access tokens into URLs.
- Logging complete Authorization headers.
- Embedding private long-lived tokens in frontend source code.
- Assuming authentication automatically grants authorization.
- Using unnecessarily long-lived access tokens.
- Failing to define how compromised tokens are revoked or replaced.
Bearer Token Security Checklist
- Use HTTPS for bearer-token transmission.
- Treat bearer tokens as sensitive credentials.
- Prefer the Authorization header for API access tokens.
- Validate tokens on every protected request.
- For JWTs, verify the signature and expected algorithm.
- Validate expiration and other required time claims.
- Validate issuer and audience when applicable.
- Apply authorization checks after authentication.
- Avoid putting tokens into URLs.
- Avoid logging complete bearer credentials.
- Use appropriate token lifetimes.
- Protect refresh tokens separately from access tokens.
- Have a strategy for revocation or replacement of compromised credentials.
- Keep private credentials out of client-side code when they must remain secret.
Frequently Asked Questions
What is a bearer token?
A bearer token is a credential that can be presented to a protected resource to obtain access according to the permissions associated with the token. Whoever possesses a valid bearer token may be able to use it.
Is a bearer token the same as a JWT?
No. Bearer describes how a credential is presented and used, while JWT is a token format. A JWT can be used as a bearer token, but bearer tokens can also be opaque random strings.
Where is a bearer token sent?
The common HTTP representation is the Authorization header using the Bearer authentication scheme, such as Authorization: Bearer token-value.
Are bearer tokens secure?
Bearer tokens can be used securely when they are transmitted over HTTPS, properly validated, protected from accidental exposure, given appropriate lifetimes, and combined with suitable authorization controls. Their possession-based nature means leakage is particularly important to prevent.
Can bearer tokens expire?
Yes. Access tokens can have defined lifetimes. JWT access tokens commonly use the exp claim to represent expiration, while opaque tokens can have expiration enforced through server-side state.
What happens if a bearer token is stolen?
An attacker who obtains a valid bearer token may be able to use it within the token's permissions until it expires or is revoked. The response depends on the token system, but exposed credentials should generally be invalidated or replaced when possible.
Should bearer tokens be stored in localStorage?
There is no universal answer for every application. localStorage is accessible to JavaScript, so an XSS vulnerability can potentially expose tokens stored there. Browser authentication architecture should consider HttpOnly cookies, CSRF protections, XSS defenses, token lifetimes, and the application's threat model.
Helpful JWT and Authentication Tools
JWT-related developer tools are useful when inspecting and debugging bearer-token authentication. JWT inspectors can help examine the overall token structure, while JWT claims viewers make registered and custom claims easier to inspect. JWT header viewers are useful for checking fields such as alg and typ, and JWT encoders can help create test JWTs in controlled development environments. A JWT expiration calculator can also make token lifetime and expiration timestamps easier to verify when troubleshooting authentication flows.
Conclusion
Bearer tokens provide a simple and widely used way to present credentials to protected APIs. The client sends the token, commonly through the Authorization header, and the server validates it before processing the request.
Bearer authentication should not be confused with JWTs. JWT is a token format, while bearer describes the way a credential is presented. Whether the token is a JWT or an opaque value, it should be treated as sensitive, transmitted over HTTPS, validated carefully, given an appropriate lifetime, and combined with explicit authorization checks.