In this article
June 3, 2025
June 3, 2025

Understanding bearer tokens: What are they and how to use them securely

The humble bearer token, explained—plus tips to use it safely and avoid common mistakes.

What gives someone—or something—access to your data once you’ve logged in? In many systems, the answer is a bearer token. These compact strings act like digital keys: anyone holding one can gain access, no questions asked. They're a core part of how modern APIs and authentication flows work, especially in protocols like OAuth 2.0.

But while bearer tokens are convenient, they’re also inherently risky. They don't verify who is using them—only that they’re valid. That makes secure handling essential. In this article, we’ll break down what bearer tokens are, why they matter, and how to use them safely without leaving your systems exposed.

What is a bearer token?

A bearer token is any token that uses the "bearer" authentication scheme (an HTTP authentication scheme that uses bearer tokens to authorize requests).

It is called a bearer token because whoever presents the token (“bears” it) is granted access — no additional proof of identity is required. Possession alone is enough for authorization.

Bearer tokens are commonly used in protocols like OAuth 2.0 and are sent with each HTTP request to authenticate the client and grant access to protected resources.

Here’s what it looks like in an HTTP header:

	
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6...
	

How bearer tokens work

Bearer tokens are typically issued after a successful authentication step (e.g., via OAuth, SSO, or a login API). The flow generally looks like this:

  1. Client authenticates with credentials or via an identity provider.
  2. Server (or authorization server) issues a bearer token.
  3. Client stores the token (in memory, local storage, etc.).
  4. Client includes the token in subsequent API requests using the Authorization HTTP header.
  5. Server validates the token:
    • If valid, grants access.
    • If expired or malformed, returns 401 Unauthorized.

Many bearer tokens are formatted as JWTs (JSON Web Tokens), which are compact, URL-safe tokens that include claims and can be cryptographically verified.

The bearer token is also usually sent over an encrypted connection via HTTPS. This prevents unauthorized access by malicious third parties even if the token is stolen.

Common pitfalls

1. Unsafe token transmission

A common problem is sending bearer tokens over HTTP (not HTTPS).

	
# Dangerous – token is exposed
curl -H "Authorization: Bearer abc123..." http://api.example.com/data
	

Bearer tokens work like passwords — if someone sees it, they can use it. Using HTTP means the token travels in plain text, which can be stolen through:

  • Man-in-the-middle (MITM) attacks.
  • Public Wi-Fi or shared networks.
  • Compromised proxies or load balancers.

You should always use HTTPS to encrypt traffic, and enable HTTP Strict Transport Security (HSTS) to force secure connections.

2. Storing tokens in insecure locations

Common bad practices:

	
// DANGEROUS - XSS can steal these
localStorage.setItem('token', bearerToken);
sessionStorage.setItem('token', bearerToken);

// DANGEROUS - visible in browser dev tools
window.authToken = bearerToken;

// DANGEROUS - logged in console/error messages
console.log('Auth token:', bearerToken);
	

Some better options include:

  • Use HttpOnly, Secure cookies for web apps.
  • Use secure storage APIs on mobile (e.g., Keychain, Keystore).
  • Keep tokens in memory when possible.
  • If persisted, encrypt them.

3. Leaking tokens in URLs and logs

	
# DANGEROUS - tokens in URL params get logged everywhere
GET /api/data?access_token=abc123...

# DANGEROUS - tokens in referer headers
<a href="https://external-site.com">Link</a>
# When clicked, the Authorization header might leak

# Server logs often capture full request URLs
2024-01-15 10:30:22 GET /api/data?token=secret123 200 OK
	

To avoid this:

  • Always use Authorization headers, never URL parameters.
  • Configure servers to sanitize logs.
  • Be careful with redirects and external links.
  • Implement proper log filtering.

4. Long-lived tokens

Tokens that live too long increase risk.

	
{
  "access_token": "...",
  "expires_in": 31536000,  // 1 year - TOO LONG
  "token_type": "bearer"
}
	

Use short-lived access tokens (15–30 mins, or less) and use refresh tokens to extend sessions securely.

5. Missing or weak token validation

	
// DANGEROUS - no validation
app.get('/api/data', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (token) {
    // Assumes any token is valid!
    return userData;
  }
});

// DANGEROUS - weak validation
if (token === 'hardcoded-secret') {
  // Allow access
}
	

You should be very careful when validating tokens. There is a series of steps that you should always follow:

  • Verify the signature using the secret key or public key.
  • Check the expiration time (exp) and the not-before time (nbf) claims to ensure the JWT is valid.
  • Verify the issuer (iss) claim to ensure the JWT was issued by a trusted party.
  • Verify the audience (aud) claim to ensure the JWT is intended for the correct recipient.
  • Verify the scopes to make sure the requested action is allowed.

For more, see JWT validation: how-to and best libraries to use.

6. Poor client-side token handling

React/JS pitfalls:

	
// DANGEROUS - token in component state without cleanup
const [token, setToken] = useState(localStorage.getItem('token'));

// DANGEROUS - token in global scope
window.myApp = {
  authToken: 'bearer-token-here'
};

// DANGEROUS - not clearing tokens on logout
const logout = () => {
  // Forgot to clear the token!
  navigate('/login');
};
	

Mobile app pitfalls:

	
// DANGEROUS - storing in UserDefaults (unencrypted)
UserDefaults.standard.set(token, forKey: "auth_token")

// DANGEROUS - hardcoded tokens in source code
let apiToken = "sk-1234567890abcdef"
	

Fixes:

  • Store tokens in HttpOnly cookies or secure app storage.
  • Clear tokens on logout.
  • Never hardcode secrets.

7. Overly broad token permissions

Too much access:

	
{
  "access_token": "...",
  "scope": "read write admin delete users billing",  // TOO BROAD
  "token_type": "bearer"
}
	

Better approach:

	
{
  "access_token": "...",
  "scope": "read:profile read:posts",  // Minimal necessary scope
  "token_type": "bearer"
}
	

Narrow scopes reduce risk if the token is stolen.

8. CSRF vulnerabilities

Automatic token inclusion enables CSRF:

	

<img src="https://api.example.com/delete-account" />
	

To prevent this:

  • Use custom headers (Authorization header) instead of cookies.
  • Implement CSRF tokens for state-changing operations.
  • Validate Origin/Referer headers.
  • Use SameSite cookie attributes when using cookie-based tokens.

9. Replay attack vulnerabilities

	
# Attacker captures this request and can replay it indefinitely
curl -H "Authorization: Bearer captured-token" \
     https://api.example.com/transfer-money
	

To avoid this:

  • Use short-lived tokens
  • Require timestamps or nonces
  • Add JWT claims like jti (unique ID)
  • Sign requests (e.g., HMAC)

10. Insecure error messages

Leaking sensitive info:

	
{
  "error": "Invalid token: eyJhbGciOi..."
}
	
  • Leaks token values in error messages
  • Provides too much information to attackers
  • May expose internal system details

Better error handling:

	
{
  "error": "unauthorized",
  "error_description": "Invalid or expired token"
}
	

Best practices for using bearer tokens

  • Always use HTTPS: Non-negotiable for bearer tokens. Never send bearer tokens over plaintext HTTP — they can be stolen.
  • Store tokens securely: Avoid storing tokens in places vulnerable to XSS (e.g., localStorage).
  • Use short lifetimes: 15-30 minutes (or less) for access tokens. Minimize damage in case of leakage.
  • Implement proper validation: Verify signatures, issuer, audience, expiration, and scope.
  • Monitor for anomalies: Unusual usage patterns, multiple simultaneous sessions.
  • Plan for compromise: Token revocation, rotation procedures.
  • Minimize scope: Least privilege principle.
  • Implement token revocation/blacklisting: Act fast if a token is compromised.
  • Secure client implementations: Proper storage, cleanup on logout.
  • Log security events: Authentication failures, token usage patterns.
  • Regular security reviews: Audit token handling code and practices.

Remember that bearer tokens are powerful but inherently risky because they're "bearer" tokens - whoever has them can use them. This makes proper handling absolutely critical for application security.

Debugging tip: Mind the case of Bearer

If you’re seeing requests mysteriously rejected—even when your token looks valid—double-check how you're formatting the Authorization header.

	
Authorization: bearer eyJhbGciOi...
	

Despite the HTTP spec (RFC 7235) stating that the auth scheme is case-insensitive, some servers and libraries expect "Bearer" to be capitalized exactly.

OAuth 2.0 (RFC 6750) uses "Bearer" consistently, and many real-world systems follow that convention strictly.

The recommended best practice is to always use the capitalized "Bearer" prefix:

	
Authorization: Bearer eyJhbGciOi...
	

This simple detail can save you from hours of debugging 401 responses, especially when integrating with OAuth-protected APIs or identity platforms.

This site uses cookies to improve your experience. Please accept the use of cookies on this site. You can review our cookie policy here and our privacy policy here. If you choose to refuse, functionality of this site will be limited.