PureTools

API Authentication: Tokens, Keys, OAuth, and Sessions

PureTools Team· 8 min read
API Authentication: Tokens, Keys, OAuth, and Sessions

API Authentication: Pick the Right Method

Every API needs authentication, but there are many ways to do it. The right choice depends on who's calling your API (users vs servers) and what security guarantees you need.

Method Comparison

MethodBest ForStateless?Complexity
API KeysServer-to-server, public APIsYesLow
JWT (Bearer Token)SPAs, mobile apps, microservicesYesMedium
Session CookiesTraditional web apps (SSR)No (server-side state)Low
OAuth 2.0Third-party access, social loginDependsHigh
Basic AuthInternal tools, debuggingYesLowest

API Keys

// Client sends key in header
GET /api/data HTTP/1.1
X-API-Key: sk_live_abc123def456

// Server validates
app.use((req, res, next) => {
  const key = req.headers['x-api-key'];
  const client = await db.apiKeys.findByKey(key);
  if (!client) return res.status(401).json({ error: 'Invalid API key' });
  req.client = client;
  next();
});

Pros: simple, no expiration management. Cons: if leaked, access until revoked. Not user-specific.

JWT Bearer Tokens

// Client sends token in Authorization header
GET /api/profile HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

// Server validates and extracts user info
import jwt from 'jsonwebtoken';

function authMiddleware(req, res, next) {
  const token = req.headers.authorization?.replace('Bearer ', '');
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET);
    req.user = payload;
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
}

Pros: stateless, scalable, carries user info. Cons: can't revoke individual tokens (without a blacklist).

Session Cookies

// Server creates session on login
app.post('/login', async (req, res) => {
  const user = await authenticate(req.body);
  req.session.userId = user.id;
  res.json({ message: 'Logged in' });
});

// Browser automatically sends cookie
// Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict

Pros: automatic (browser handles it), HttpOnly prevents XSS theft, easy to invalidate. Cons: requires server-side session store, CSRF protection needed, doesn't work well for mobile/SPAs.

When to Use What

ScenarioRecommended
Public API for developersAPI Keys
SPA calling your own APIJWT + Refresh Token
Server-rendered web appSession Cookies
Mobile appJWT + Refresh Token
"Login with Google"OAuth 2.0
Microservice to microserviceJWT or mTLS
Quick internal toolBasic Auth (over HTTPS)

Security Essentials

  • Always use HTTPS. Any auth method is insecure over HTTP.
  • Store secrets properly. API keys in env vars, tokens in httpOnly cookies or secure storage.
  • Implement rate limiting on auth endpoints to prevent brute force.
  • Short-lived tokens with refresh tokens > long-lived tokens.
  • Log auth events — failed logins, token refreshes, key creation.

Decode your tokens: JWT Decoder — inspect token claims, expiration, and signatures.