API Authentication Methods

Basic auth, API keys, sessions, JWT bearer tokens and OAuth 2.0 compared.

Intermediate9 min read3 interview questions

Authentication answers “who is calling?”. Different callers — a browser user, a mobile app, a partner server, an internal service — suit different methods.

For most modern APIs the answer is OAuth 2.0 with short-lived JWT access tokens, issued by an identity provider rather than by your own code.

Diagram

1. sign in2. access token (JWT)3. Bearer token4. verify signatureClient appIdentity providerEntra ID, Auth0, KeycloakResource APIvalidates tokenSigning keysJWKS endpoint
The identity provider issues a signed token; the API verifies it without calling the provider on every request.

Key concepts

Basic auth
Username and password in every request header. Only acceptable over HTTPS for simple internal tools.
API key
A secret string identifying the calling application. Simple for server-to-server, but it identifies an app, not a user.
Session cookie
Server stores the session; the browser sends a cookie. Good for classic web apps; needs CSRF protection.
JWT
A signed, self-contained token with claims (user, roles, expiry). Stateless to verify; hard to revoke before expiry.
OAuth 2.0
A framework for delegated access. Authorization Code + PKCE for apps with users; Client Credentials for services.
OpenID Connect
An identity layer on OAuth 2.0 that adds an ID token describing the user.

Trade-offs

Benefits

  • Tokens let APIs verify callers without a database lookup
  • An external identity provider gives MFA, SSO and auditing for free
  • Scopes limit what each token can do

Costs

  • JWTs can’t be revoked instantly without extra machinery
  • OAuth flows are complex to implement yourself
  • API keys leak easily and are long-lived

Use it when

  • OAuth 2.0 + OIDC for apps with user sign-in
  • Client credentials or managed identity for service-to-service
  • API keys for simple partner integrations with IP restrictions

Common mistakes

  • Storing JWTs in localStorage where XSS can read them
  • Not validating aud, iss and expiry claims
  • Accepting the none algorithm or letting the token choose its own algorithm
  • Putting sensitive data in JWT claims — they are only encoded, not encrypted

Interview questions

Q1Is a JWT encrypted?
Usually not. A standard JWT is signed, which proves it was not tampered with, but anyone can base64-decode and read its claims.
Q2Which OAuth flow should a single-page app use?
Authorization Code with PKCE. The implicit flow is deprecated because tokens were exposed in the URL.
Q3How can you revoke a JWT before it expires?
Keep access tokens short-lived (5–15 minutes) and revoke the refresh token, or maintain a deny list of token IDs checked on each request.