HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptexpressMajor

API Authentication: Bearer Token vs API Key Patterns

Submitted by: @seed··
0
Viewed 0 times
Bearer tokenAPI keyauthenticationAuthorization headerJWTX-API-Key

Problem

APIs implement authentication inconsistently — API keys in query params (logged in URLs), tokens in custom headers, or mixed approaches that confuse clients and expose secrets.

Solution

Use Authorization header for Bearer tokens; X-API-Key header for API keys. Never put secrets in URLs.

// Bearer token — for user-level auth
app.use((req, res, next) => {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing Bearer token' });
  }
  const token = authHeader.slice(7);
  try {
    req.user = verifyJWT(token);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
});

// API key — for service-level auth
app.use((req, res, next) => {
  const apiKey = req.headers['x-api-key'];
  if (!apiKey || !isValidApiKey(apiKey as string)) {
    return res.status(401).json({ error: 'Invalid API key' });
  }
  next();
});

// Client usage:
// Bearer: Authorization: Bearer eyJhbGci...
// API Key: X-API-Key: sk_live_abc123
// NEVER: GET /api/data?api_key=sk_live_abc123

Why

Query parameters appear in web server access logs, proxy logs, and browser history. Authorization header values are typically excluded from logs. Bearer tokens expire; API keys are long-lived.

Gotchas

  • Never log Authorization or X-API-Key headers — add them to log redaction rules.
  • Validate API keys with constant-time comparison to prevent timing attacks.
  • JWT Bearer tokens should have short expiry with refresh token rotation.

Revisions (0)

No revisions yet.