API Authentication Methods — API Keys, JWT, OAuth 2.0

Why API Authentication Matters

APIs that are publicly accessible without authentication are a security disaster waiting to happen. Authentication ensures that only authorized users, applications, or services can access your API. It also enables rate limiting, usage tracking, and billing.

Why this matters for your career:

  • API security is the #1 concern for businesses exposing data via APIs
  • Authentication implementation is a common freelance project requirement
  • Understanding OAuth 2.0 and JWT is expected for mid-level backend roles
  • Security breaches from poor authentication can cost companies millions

What Is API Authentication?

API authentication verifies the identity of the client making the request. It answers the question: "Who is calling this API?" Authorization (which comes next) answers: "What are they allowed to do?"

The most common authentication methods for APIs are:

  1. API Key — Simple, shared secret key
  2. Bearer Token (JWT) — Self-contained, signed token
  3. OAuth 2.0 — Delegated authorization framework
  4. Basic Auth — Username + password (legacy, not recommended)

API Keys

API keys are the simplest form of authentication. The client sends a key in the header or query parameter:

GET /api/v1/products
X-API-Key: abc123def456

Or:

GET /api/v1/products?api_key=abc123def456

Pros and Cons

| Pros | Cons | |------|------| | Simple to implement | Shared secret — anyone with the key has access | | Easy for clients to use | Hard to rotate without downtime | | Works for server-to-server | No identity granularity (one key = one user) | | No complex setup | Vulnerable if exposed in client-side code |

Best Practices for API Keys

  • Generate keys using cryptographically random strings (e.g., uuidv4)
  • Store keys hashed in your database (never plaintext)
  • Allow multiple keys per user (rotate without disruption)
  • Support key revocation
  • Rate limit per key
  • Never embed API keys in client-side JavaScript

JWT (JSON Web Tokens)

JWT is a compact, self-contained token format. The token itself contains the user's identity and claims, digitally signed so it cannot be tampered with.

JWT Structure

A JWT consists of three parts separated by dots:

header.payload.signature

Header:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload:

{
  "sub": "user_12345",
  "name": "John Doe",
  "role": "admin",
  "iat": 1516239022,
  "exp": 1516242622
}

Signature: Created by signing the header + payload with a secret key.

How JWT Authentication Works

  1. User logs in with credentials → server validates and returns a JWT
  2. Client stores the JWT (in memory, localStorage, or httpOnly cookie)
  3. Client sends the JWT in the Authorization header:
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
    
  4. Server verifies the signature and extracts user info from payload
  5. No database lookup needed — the token is self-validating

JWT Implementation Example (Node.js)

const jwt = require('jsonwebtoken');

// Sign a token
const token = jwt.sign(
  { sub: 'user_12345', role: 'admin' },
  process.env.JWT_SECRET,
  { expiresIn: '1h' }
);

// Verify a token (middleware)
function authMiddleware(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing token' });
  }

  const token = authHeader.split(' ')[1];

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid or expired token' });
  }
}

JWT Best Practices

  • Use strong secrets (at least 256 bits for HS256)
  • Set short expiration times (15 min to 1 hour)
  • Use refresh tokens for longer sessions
  • Store tokens securely (httpOnly cookies preferred over localStorage)
  • Include minimal claims in the payload (don't store sensitive data)
  • Rotate signing keys periodically

OAuth 2.0

OAuth 2.0 is not an authentication protocol — it is an authorization framework. However, it is commonly used for authentication via the OpenID Connect layer on top.

OAuth 2.0 Flows

| Flow | Use Case | |------|----------| | Authorization Code | Web apps with backend server (most secure) | | PKCE (Proof Key for Code Exchange) | Mobile and single-page apps | | Client Credentials | Server-to-server communication | | Implicit (deprecated) | Legacy SPAs (do not use) |

Authorization Code Flow (Simplified)

  1. User clicks "Login with Google"
  2. Browser redirects to Google's authorization page
  3. User approves the requested permissions
  4. Google redirects back with an authorization code
  5. Backend exchanges the code for an access token
  6. Backend uses the access token to call Google APIs on behalf of the user

Why OAuth 2.0 Matters

  • Used by Google, Facebook, GitHub, Stripe, and all major platforms
  • Enables "Login with ..." buttons across the web
  • Allows delegated access without sharing passwords
  • Industry standard for third-party API access

Comparison Table

| Method | Complexity | Security | Use Case | |--------|-----------|----------|----------| | API Key | Low | Medium | Server-to-server, simple integrations | | JWT Bearer Token | Medium | High | User authentication, stateless APIs | | OAuth 2.0 | High | Very High | Third-party access, social login | | Basic Auth | Low | Low | Legacy systems, internal tools |

Common Authentication Mistakes

| Mistake | Why It's Dangerous | |---------|-------------------| | Tokens in URL query params | Logged in server logs, visible in browser history | | No expiration on tokens | Stolen tokens work forever | | Storing tokens in localStorage | Vulnerable to XSS attacks | | Using Basic Auth over HTTP | Credentials sent in plaintext | | Hardcoded API keys in code | Exposed in GitHub repos | | No rate limiting per key | Abuse and brute force attacks | | Weak JWT secrets | Tokens can be forged |

Summary

API authentication is the first line of defense for your APIs. Choose the right method based on your use case: API keys for simple server-to-server, JWT for user-facing web APIs, and OAuth 2.0 for third-party integrations. Always follow security best practices — use HTTPS, short token lifetimes, secure storage, and proper validation.

Key takeaways:

  • API keys are simple but limited — good for server-to-server
  • JWT tokens are self-contained and stateless — ideal for modern web APIs
  • OAuth 2.0 is the standard for delegated authorization
  • Never expose tokens in URLs, client-side code, or unsecured storage
  • Always use HTTPS and validate tokens on every request
  • Set expiration times and implement refresh token rotation

What's Next: API Mocking with Vibe

The next chapter teaches you how to mock APIs using Vibe, enabling frontend development to proceed before the backend is complete.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!