Skip to content
NewsDataHub NewsDataHub Learning Center

How Does API Authentication Work? Understanding API Keys, Tokens, and OAuth

When you use an app to check the weather, post on social media, or access your bank account, the app needs to prove it has permission to access that data on your behalf. This is where API authentication comes in — the security layer that ensures only authorized applications and users can access protected resources.

Understanding API authentication is crucial for anyone working with modern applications. Whether you’re integrating with third‑party services, building your own APIs, or simply curious about how app security works, these authentication methods are the gatekeepers that keep the digital world secure.

Authentication vs Authorization: The Important Distinction

Section titled “Authentication vs Authorization: The Important Distinction”
  • Authentication: Who are you? Verifying identity
  • Authorization: What can you do? Determining permissions

Example

  • Authentication: The app verifies you are who you claim to be (username and password)
  • Authorization: The system checks what you’re allowed to do (read, write, admin)

Most API auth schemes touch both, but they solve different problems.

  • API Keys: Basic key cards that open specific doors
  • Bearer Tokens: Temporary visitor badges with time limits
  • OAuth: Valet system where you grant limited access without sharing your actual keys

Simple, long‑lived credentials that identify and authenticate your application.

GET /api/v1/resources HTTP/1.1
Host: [api.example.com](http://api.example.com)
X-API-Key: sk_live_abc123def456
  • Header‑based (most common)
Terminal window
curl -H "X-API-Key: YOUR_KEY" https://api.example.com/api/v1/resources
  • Query parameter (insecure — avoid)
Terminal window
curl "https://api.example.com/api/v1/resources?api_key=YOUR_KEY"

⚠️ Never put keys in URLs. They leak into server logs, browser history, analytics, and referrer headers.

  • Authorization header (some providers)
Terminal window
curl -H "Authorization: Bearer YOUR_KEY" https://api.example.com/api/v1/resources
  • Server‑to‑server integrations
  • Simple internal services
  • Public or low‑risk data
  • Never expose keys in client‑side code
  • Always use HTTPS
  • Rotate keys and scope permissions narrowly

A very old pattern that encodes username:password in Base64. Avoid for modern APIs.

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

Base64 is not encryption; it’s easily reversible. If you must support it, require HTTPS, short lifetimes, and limited scopes.


Short‑lived credentials (often JWTs) presented in the Authorization header.

GET /api/v1/user/profile HTTP/1.1
Host: [api.example.com](http://api.example.com)
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Many bearer tokens use the JWT format: header.payload.signature

  • Header: {"alg":"HS256","typ":"JWT"}
  • Payload: {"user_id":123,"exp":1640995200}
  • Signature: cryptographic verification

What the signature prevents

  • Detects tampering: if someone edits the header or payload, signature verification fails
  • Proves authenticity: only the signer (or key holder) can produce a valid signature

Note: JWTs are only as trustworthy as your key management and verification logic. Never trust a JWT you haven’t verified.

  1. User authenticates with credentials or an OAuth grant
  2. Server issues a short‑lived access token and a longer‑lived refresh token
  3. Client calls APIs with the access token in Authorization: Bearer …
  4. When the access token expires, the client exchanges the refresh token for a new access token
  5. Server may rotate refresh tokens and revoke old ones

Benefits: short access token lifetimes reduce risk; refresh tokens let sessions continue without prompting for credentials.

  • User‑specific data and permissions
  • Mobile and SPA frontends
  • Anywhere you want automatic expiration and revocation

A framework for granting limited access without sharing passwords.

Participants (plain language)

  • User: the person who owns the data
  • Client app: the app asking for limited access
  • Authorization server: the place the user signs in and grants consent
  • Resource server: the API that holds the data

Concrete flow (Authorization Code with PKCE, simplified)

  1. App sends user to the authorization server with requested scopes
  2. User signs in and reviews the requested access
  3. User consents; authorization server redirects back with a one‑time code
  4. App’s backend exchanges the code for tokens (access token, optionally refresh token)
  5. App calls the resource server using Authorization: Bearer ACCESS_TOKEN
  6. When the access token expires, app uses the refresh token to get a new access token (until revoked or expired)

Security benefits

  • The app never sees the user’s password
  • Users can grant only specific scopes and revoke later
  • Short‑lived access tokens, refresh‑based continuation

  • 401 Unauthorized: Missing or invalid credentials. Fix by including valid Authorization headers or signing in.
  • 403 Forbidden: You are authenticated, but lack permission for this resource or action. Fix by requesting proper scopes or roles.

  • Always use HTTPS
  • Keep secrets out of URLs and client‑side code
  • Scope credentials narrowly and rotate them
  • Prefer short‑lived access tokens plus refresh tokens
  • Verify JWTs server‑side and validate exp, aud, iss, and signature
  • Log auth failures with enough context, but never log secrets
  • Putting keys in frontend code or mobile apps
  • Long‑lived tokens with no rotation
  • Accepting JWTs without verifying signature and claims
  • Using 200 responses for auth failures instead of proper 401 or 403

Header API key

X-API-Key: sk_live_abc123

Bearer token

Authorization: Bearer eyJhbGciOi...

Basic auth (legacy)

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

JWT structure (compact)

header.payload.signature

Consult these authoritative sources to learn more:

  1. What’s the difference between authentication and authorization?
  • Authentication answers “Who are you?” using proofs like passwords, OTPs, or federated identities. Authorization answers “What are you allowed to do?” via roles, scopes, and policies. In code, authN typically happens at the edge (middleware) to establish a principal, and authZ is enforced per route or resource with RBAC/ABAC checks. Tests should cover both: rejected requests without identity, and denied requests with insufficient permission.
  1. Why are API keys in query parameters insecure?
  • URLs are widely logged by proxies, servers, CDNs, and browsers, so keys in query strings leak into logs, history, analytics, and referrer headers. They’re also easier to shoulder‑surf and accidentally share. Prefer headers over HTTPS, disable query‑string auth, and redact query strings in logs. If you must support legacy clients, gate by IP, apply strict rate limits, and migrate to headers ASAP.
  1. What does a JWT signature actually protect?
  • Integrity and authenticity. A valid signature proves the token was issued by a trusted signer and has not been altered (header or payload). It does not provide confidentiality; JWT payloads are usually base64url‑encoded, not encrypted. In services, always verify signature, exp, iss, aud, and optionally nbf. Rotate signing keys, use strong algorithms (avoid none), and reject tokens signed with unexpected algs.
  1. When do you choose OAuth over simple bearer tokens?
  • Use OAuth when a third‑party identity or consented access is required, such as “Sign in with X” or accessing a user’s data at another provider. OAuth provides scoped, revocable access and separates the roles of authorization server and resource server. For first‑party apps with no external identity, a simple login plus server‑issued bearer tokens may suffice.
  1. How does a refresh token flow work and why use it?
  • The server issues a short‑lived access token and a longer‑lived refresh token. Clients call APIs with the access token; when it expires, they exchange the refresh token for a new access token (often rotating the refresh token). Benefits: limits exposure if an access token leaks, reduces re‑authentication prompts, and supports session revocation by invalidating refresh tokens. Store refresh tokens securely (httpOnly cookies or secure storage), bind them to client context if possible, and monitor unusual reuse patterns.
  • What’s the difference between authentication and authorization?

    Authentication verifies who you are (like showing ID), while authorization determines what you’re allowed to do (like having permission to enter a room). APIs need both: auth proves identity, authz grants access.

  • Which authentication method should I use for my API?

    Use API keys for server-to-server communication, OAuth for third-party user data access, and JWT tokens for stateless distributed systems. Always use HTTPS regardless of method.

  • Are API keys safe to use in mobile apps?

    No. Never embed API keys in client-side code or mobile apps - they can be extracted through reverse engineering. Use a backend proxy to make authenticated API calls.

  • How often should I rotate API keys?

    Rotate keys every 90 days minimum, immediately after team member departures, and whenever there’s a potential security breach. Use automated key rotation for production systems.

  • What’s the difference between access tokens and refresh tokens?

    Access tokens are short-lived (minutes to hours) and used to access resources. Refresh tokens are long-lived and used only to obtain new access tokens, reducing exposure if an access token is compromised.

Olga S.

Founder of NewsDataHub — Distributed Systems & Data Engineering

Connect on LinkedIn