Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Authentication Basics

HTTP Basic Auth and API Keys

Understand HTTP Basic authentication (Authorization header, Base64, WWW-Authenticate) and API keys: generating, hashing, scoping, rotating and revoking them safely.

The simplest ways to authenticate an API call are a username and password in a header (HTTP Basic) and a long secret string issued to a developer (an API key). Both are easy to implement and easy to use from curl, scripts and other servers, so you will meet them often. Both are also easy to get wrong. This lesson shows how they work on the wire and how to implement them safely.

HTTP Basic authentication

Basic auth is defined in the HTTP standard itself. The flow:

  1. The client calls a protected URL without credentials.
  2. The server answers 401 with WWW-Authenticate: Basic realm="Orders API".
  3. The client repeats the request with Authorization: Basic <credentials>, where <credentials> is the Base64 encoding of username:password.
HTTP
GET /orders HTTP/1.1
Authorization: Basic YWRhOnNlY3JldA==

YWRhOnNlY3JldA== is just ada:secret in Base64. Base64 is an encoding, not encryption: anyone who sees the header reads the password. Therefore:

  • Basic auth must only ever be used over HTTPS.
  • The browser caches the credentials and sends them with every request to that origin until it is closed, so it is a poor fit for browser applications.
  • There is no built-in logout, expiry or MFA.

Because of these weaknesses, Basic auth is mostly used for simple internal tools, quick scripts, and as the client-authentication step of other protocols (OAuth token endpoints use client id and secret this way).

A note on parsing: the username must not contain a colon, and the password may. So split on the first colon only.

Node.js Basic auth: encode, send and verify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

(fetch also accepts credentials in the URL, http://user:pass@host, but passwords in URLs end up in logs; always use the header.)

API keys

An API key is a long random secret that identifies the calling application or developer rather than a person. Services such as payment gateways, maps and email providers issue them. A client sends the key in a header, typically Authorization: Bearer sk_live_... or a custom header such as X-API-Key.

Keys are popular because they are trivially simple, never expire unless you make them, and map directly to a customer account for billing and rate limits. They are not a user identity, and they are weaker than short-lived tokens: whoever has the string is the caller. So the discipline around them matters.

Designing good keys

  • High entropy: at least 128 bits of randomness from a cryptographic source (crypto.randomBytes(32)), never a counter, timestamp or user-chosen value.
  • A readable prefix that tells the type and environment: pk_test_, sk_live_. Prefixes make leaks recognisable and let secret scanners (GitHub's, for example) detect and revoke them automatically.
  • A separate public id (the first characters) so you can look a key up and show sk_live_a1b2...c3d4 in a dashboard without storing the secret.
  • Scopes: each key lists what it may do (orders:read, orders:write). Give the minimum.
  • Metadata: name, owner, creation date, last-used time, optional expiry and IP allow-list.

Store hashes, not keys

Treat a key like a password: show it to the user once at creation, store only a hash. Unlike passwords, keys are already high-entropy random strings, so a fast hash such as SHA-256 is fine (a slow hash would only add cost to every API call). Verify by hashing the presented key and comparing in constant time.

sequenceDiagram
    participant D as Developer
    participant S as Server
    D->>S: Create key (name, scopes)
    S-->>D: sk_live_ab12... (shown once)
    Note over S: Stores prefix, SHA-256 hash, scopes
    D->>S: GET /orders + Authorization Bearer sk_live_ab12...
    S->>S: hash(presented), find by prefix, compare
    S-->>D: 200 or 401 / 403 if scope missing

Only a hash of the key lives on the server.

Node.js Issue, verify, scope and revoke API keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Because only hashes are stored, a leaked database does not leak working keys. Because keys have scopes, a leaked read-only key cannot write. Because revocation is a single flag, a compromised key can be killed instantly.

Where to send the key

Place Verdict
Authorization: Bearer <key> header Best: standard, stays out of logs by default
Custom header (X-API-Key) Acceptable and common
Query string (?api_key=...) Avoid: URLs are logged by proxies, browsers and CDNs, and leak through Referer
Request body Avoid for GET-style APIs; awkward

Operating keys safely

  • Rotation: support at least two active keys per account so clients can switch without downtime, then revoke the old one.
  • Never in client-side code: a key shipped in a mobile app or web page is public. Browser and mobile apps should use user-level tokens (coming later in this course) and let your server hold the secret keys.
  • Secret scanning: the key prefix lets tools detect committed keys. Offer a revoke-on-leak flow.
  • Rate limit and monitor per key, and show a last-used timestamp so owners can spot misuse.
  • HTTPS only, always.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the Authorization header value for Basic auth with user ada and password secret?

    The header is "Basic " plus Base64("ada:secret"). Base64 is reversible, so HTTPS is mandatory.
  2. 2. Why can a password contain colons but a Basic auth username cannot?

    Parsers split at the first colon, so everything after it belongs to the password.
  3. 3. How should a server store issued API keys?

    Like passwords, keys should be stored as hashes. High-entropy keys can use fast SHA-256.
  4. 4. Why is sending an API key in the query string discouraged?

    Prefer the Authorization header so keys stay out of access logs and browser history.
  5. 5. A mobile app needs to call your API. Where should a powerful secret API key live?

    Anything shipped to a client can be extracted. Use per-user tokens in clients and keep secret keys on servers.

Summary

  • Basic auth sends Base64(username:password) in Authorization; it is not encryption, so use HTTPS only, and it has no logout, expiry or MFA.
  • API keys identify an application; generate them from a secure random source with a type prefix, scopes and metadata.
  • Show a key once, store only its hash, compare in constant time, and support scopes, rotation and instant revocation.
  • Send keys in headers, never in URLs, and never ship secret keys to browsers or mobile apps.
  • Return 401 for missing or invalid keys and 403 when a valid key lacks the scope.

Next: Sessions and Cookies