100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What Are the Main API Authentication Methods?

Compare API keys, Basic Auth, sessions, and JWT bearer tokens for API authentication, with tradeoffs and code examples.

mediumQ109 of 224 in Web Development Est. time: 6 minsLast updated:
Open Code Lab

Expected Interview Answer

The most common API authentication methods are API keys for simple service-to-service identification, HTTP Basic Auth for quick but weak username/password checks, session cookies for traditional server-rendered apps, and bearer tokens like JWTs or OAuth access tokens for stateless, scalable authentication of modern APIs.

An API key is a static secret string sent in a header or query parameter that identifies the calling application, simple to implement but offering no built-in expiry or user-level granularity, so it is best for server-to-server or rate-limiting use cases rather than end-user identity. HTTP Basic Auth sends a base64-encoded username:password on every request, which is easy to set up but must run over TLS and lacks token expiry or scoping, making it unsuitable beyond quick internal tools. Session-based authentication issues an opaque session ID stored in a cookie after login, with the server keeping session state (in memory or a store like Redis), which works well for traditional web apps but requires sticky sessions or a shared store to scale horizontally. Bearer tokens, most commonly JWTs, are self-contained and signed, so any server can verify them without a database lookup, enabling stateless horizontal scaling and standardized delegation via OAuth 2.0 flows โ€” but the tradeoff is that a compromised or stolen JWT is valid until it expires and cannot be easily revoked without extra infrastructure like a blocklist. Choosing between them is really a choice about statefulness, revocation needs, and whether the caller is a human user, another service, or a third-party app acting on a user\u2019s behalf.

  • API keys give simple, low-overhead identification for service-to-service traffic
  • Session cookies integrate naturally with browser-based, server-rendered authentication flows
  • Bearer tokens (JWTs) enable stateless verification, letting APIs scale horizontally without shared session storage
  • OAuth-based bearer tokens support scoped, delegated, revocable third-party access

AI Mentor Explanation

An API key is like a stadium vendor\u2019s permanent supplier badge โ€” it identifies which company is delivering goods, but anyone holding the badge gets the same access indefinitely. A session cookie is like a wristband issued at the gate that the venue tracks against a guest list at the entrance desk for the whole match; if the wristband is lost, the desk record still exists to verify the holder. A bearer token like a JWT is like a self-verifying ticket stub with an embedded holographic seal โ€” any gate can check the seal itself without calling back to the ticket office, but if the stub is stolen, whoever holds it gets in until it expires.

Step-by-Step Explanation

  1. Step 1

    Identify the caller type

    Determine whether the caller is a human user, another service, or a third-party app acting on a user\u2019s behalf.

  2. Step 2

    Match the method to statefulness needs

    Choose sessions for stateful server-rendered apps, or bearer tokens for stateless, horizontally scaled APIs.

  3. Step 3

    Consider revocation requirements

    If instant revocation matters, favor sessions or short-lived tokens with a refresh flow over long-lived stateless JWTs.

  4. Step 4

    Layer in transport security

    Require TLS for every method, since API keys, Basic Auth credentials, and bearer tokens are all readable if sent over plain HTTP.

What Interviewer Expects

  • Clear comparison of API keys, Basic Auth, sessions, and bearer tokens/JWTs
  • Understanding of the statefulness tradeoff between sessions and JWTs
  • Awareness that JWTs are hard to revoke before expiry without extra infrastructure
  • Knowledge of when each method is the appropriate choice

Common Mistakes

  • Treating API keys as equivalent to full user authentication
  • Using HTTP Basic Auth over plain, unencrypted HTTP
  • Assuming JWTs can be instantly revoked like a server-side session
  • Not distinguishing authentication (who you are) from authorization (what you can do) in the answer

Best Answer (HR Friendly)

โ€œAPI keys are simple static secrets used mostly to identify which app is calling a service, sessions use a cookie the server tracks to remember a logged-in user, and bearer tokens like JWTs are signed tokens that any server can verify on its own without checking a database, which makes them great for scaling but harder to revoke instantly if one gets stolen.โ€

Code Example

API key check vs verifying a JWT bearer token in Express
const jwt = require('jsonwebtoken')

// API key: simple static-secret check for service-to-service calls
function requireApiKey(req, res, next) {
  if (req.headers['x-api-key'] !== process.env.PARTNER_API_KEY) {
    return res.status(401).json({ error: 'Invalid API key' })
  }
  next()
}

// Bearer token: stateless verification, no database lookup needed
function requireBearerToken(req, res, next) {
  const authHeader = req.headers.authorization || ''
  const token = authHeader.replace('Bearer ', '')

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

Follow-up Questions

  • How would you revoke a compromised JWT before it naturally expires?
  • When would you choose session-based auth over stateless JWTs for a new API?
  • How does OAuth 2.0 relate to bearer token authentication?
  • Why should API keys be rotated periodically even without a known breach?

MCQ Practice

1. What is the main scalability advantage of bearer tokens like JWTs over server-side sessions?

Because JWTs are self-contained and signed, any server instance can verify them without a database or shared cache lookup, enabling stateless horizontal scaling.

2. What is the main drawback of JWTs compared to server-side sessions?

Since JWTs are verified without a database lookup, instant revocation requires extra infrastructure like a blocklist; sessions can be invalidated immediately by deleting server-side state.

3. What is a key limitation of a plain API key as an authentication method?

API keys are usually static, coarse-grained credentials for an app or service, lacking per-user identity, scoping, and expiry unless a system is built around them.

Flash Cards

What does an API key typically identify? โ€” The calling application or service, not an individual end user.

How does session-based auth work? โ€” A cookie holds an opaque session ID the server looks up against its own stored session state.

Why are JWTs stateless? โ€” They are self-contained and signed, so any server can verify them without a database lookup.

Main JWT tradeoff? โ€” Fast, stateless verification, but hard to revoke instantly before expiry without extra infrastructure.

1 / 4

Continue Learning