Authentication Tokens and API Keys: Choose the Right Tool for the Job
IntroductionDev EnvironmentClientTransportServerAppDataMore

Authentication Tokens and API Keys: Choose the Right Tool for the Job

March 21, 2025

Authentication tokens and API keys serve different roles in API security — and it's precisely their confusion or misuse that leads to real vulnerabilities. A hardcoded API key in a public repository, a token with no expiration date, a production key used in a development environment — these aren't junior developer mistakes. They happen in mature teams when there are no clear rules about what a given credential is and how it should be used.

The Threat — Stolen or Abused Credentials

API keys and tokens are credentials. Like any credentials, they can leak — and the consequences depend on what they represent and how long they remain valid.

The most common scenarios:

Hardcoded keys in source code — an API key committed to a repository (even a private one) is immediately visible in git history. If the repo ever becomes public, or if an attacker gains access to the repo, the key is theirs. Bots actively scan GitHub for leaked keys — the time between a commit and a bot finding it is measured in minutes.

Tokens with no expiration date — a token that never expires is a stolen identity forever. One leak = permanent access.

The same key across different environments — if the development and production keys are identical, anyone with access to the development environment has access to production.

Token in the wrong place — a token in localStorage is accessible via JavaScript, which means XSS can steal it. A token in a URL ends up in server logs, browser history, and the Referer header.

Consequences

A stolen application API key: an attacker can use the API on behalf of your application, consuming rate limits, generating costs, performing operations on data. A stolen user token: the attacker acts as that user — reads data, performs operations, may escalate privileges. Both cases often go unnoticed for a long time because the requests look legitimate.


API Keys: Application Identity

API keys are simple string identifiers that authenticate the application or service making the request, not the end user. They function similarly to application-level passwords.

When to Use API Keys

API keys work well for:

  • Service-to-service communication between your internal systems
  • Identifying which application is making requests (analytics, usage quotas)
  • Simple authentication for public APIs with limited sensitivity
  • Allowing customers to access their allocated quota of resources
  • Developer-focused APIs where distribution of credentials is controlled

API Key Implementation Best Practices

Despite their simplicity, API keys require careful implementation:

  • Transmit API keys via request headers rather than embedding them in URLs
  • Use different API keys for different environments (development, staging, production)
  • Implement key rotation capabilities so compromised keys can be replaced
  • Consider implementing IP restrictions for API keys in high-security scenarios
  • Store API keys securely in environment variables or secure vaults, never in code repositories

Authentication Tokens: User Identity

Authentication tokens verify the identity of individual users, typically after they've provided credentials through a login process. Modern token approaches include JSON Web Tokens (JWT), OAuth tokens, and SAML tokens.

Types of Authentication Tokens

Session Tokens: Traditional session-based authentication that maintains state on the server. The token is simply an identifier that maps to session data stored server-side.

JWT (JSON Web Tokens): Self-contained tokens that include claims about the user and are signed to verify authenticity. They're stateless, meaning the server doesn't need to store session information.

OAuth 2.0 Tokens: Used for delegated access, allowing third-party applications to access resources on behalf of users without exposing their credentials.

Refresh Tokens: Long-lived tokens that can obtain new access tokens when the current ones expire, improving security while maintaining user convenience.

Authentication Token Implementation Best Practices

  • Keep tokens short-lived (typically minutes to hours) to minimize damage from theft
  • Implement token expiration and rotation
  • Store tokens securely (HTTP-only cookies for web applications)
  • Include only necessary claims in JWTs to minimize token size
  • Verify token signatures on every request
  • Implement a token revocation mechanism for security incidents

Using Both Together

Many sophisticated APIs use both authentication tokens and API keys for different purposes:

  1. API Key: Identifies which application is making the request
  2. Authentication Token: Identifies which user is using the application

This dual approach provides several benefits:

  • More granular analytics and rate limiting
  • Better audit trails (which user AND which application performed an action)
  • Ability to revoke either application access or individual user access
  • Defense in depth if one credential is compromised

Security Considerations

Token Storage

  • Browser-based applications: HTTP-only cookies with Secure and SameSite attributes
  • Mobile applications: Secure storage mechanisms like Keychain (iOS) or Encrypted SharedPreferences (Android)
  • Server applications: Environment variables or secure credential stores

Token Leakage Prevention

  • Never log tokens in application logs
  • Implement token entropy (sufficient randomness)
  • Use HTTPS to prevent interception
  • Set appropriate CORS policies to prevent cross-origin theft

When Things Go Wrong: Revocation Strategies

Even with perfect implementation, credentials can be compromised. Have strategies ready:

API Key Revocation: Immediately invalidate compromised API keys and issue new ones.

Token Blacklisting: Maintain a list of invalidated tokens that should be rejected despite having valid signatures.

Forced Token Refresh: For widespread compromise, force all tokens to be refreshed by changing signing keys or session validation.

Why It Works

Short token lifetimes — a stolen token is useless after a few dozen minutes. It doesn't eliminate the threat, but it drastically shortens the attack window. Long-lived tokens are effectively passwords with no rotation mechanism.

Separate keys per environment — a compromised development environment doesn't mean a compromised production environment. Credential isolation equals risk isolation.

HttpOnly cookie instead of localStorage — a token stored in an HttpOnly cookie is inaccessible to JavaScript, which eliminates theft via XSS. The browser sends it automatically with every request, but the JS code never "sees" it.

Revocation mechanism — credentials that can be immediately invalidated give you real control in an incident. Without revocation, the only option is changing the signing key and forcing all users to log in again.

Summary

API keys and authentication tokens are complementary tools, not interchangeable ones. An API key identifies the application; a token identifies the user. A few principles:

  • API keys: headers (not URLs), separate per environment, rotation, storage in a secrets vault
  • Tokens: short lifetimes, HttpOnly cookie for web apps, revocation mechanism, signature verification on every request
  • Never log credentials — neither keys nor tokens

For broader context on authentication strategies — including password hashing, 2FA, and social login — see Basic User Authentication Strategies. If you're looking for an explanation of what distinguishes authentication (who are you?) from authorization (what are you allowed to do?): Authentication vs. Authorization.


Źródła: OWASP — Authentication Cheat Sheet, OWASP — JSON Web Token Cheat Sheet