REST API Security · Lesson 15 of 30
REST API Authentication: API Keys, Basic, Bearer, OAuth 2.0
Two questions guard every protected endpoint. Authentication: who is calling? Authorisation: are they allowed to do this? REST APIs are stateless, so the caller proves who they are on every request, usually in the Authorization header. Which credential you use depends on who the caller is – a server, a mobile app, a user in a browser, or a third-party app acting on a user's behalf.
In this lesson
- The main authentication methods compared
- API keys done properly – a working example
- OAuth 2.0 flows in plain words
- Choosing the right method
The methods
| Method | Looks like | Good for | Watch out |
|---|---|---|---|
| API key | X-Api-Key: sk_live_… or Authorization: Bearer sk_… | server-to-server, identifying an app or account | long-lived; never in browser or mobile code |
| HTTP Basic | Authorization: Basic base64(user:pass) | simple internal tools, token endpoints | base64 isn't encryption – HTTPS only |
| Bearer token (JWT or opaque) | Authorization: Bearer eyJ… | users of your own apps after login | short lifetimes, secure storage |
| Session cookie | Cookie: sid=… | a browser front end on the same site | CSRF protection, SameSite cookies |
| OAuth 2.0 / OpenID Connect | access tokens issued by an authorisation server | third-party access, "Log in with Google", enterprise SSO | pick the right flow; use a proven library or provider |
| Mutual TLS | client certificate in the TLS handshake | high-security B2B and banking integrations | certificate management |
API keys done properly
// server.js
import express from 'express';
import { createHash, timingSafeEqual } from 'node:crypto';
const app = express();
const sha256 = (s) => createHash('sha256').update(s).digest();
// Store only a HASH of each key – like passwords. Show the key to the customer once, when created.
const issuedKey = 'lf_live_' + 'k3y'.repeat(8); // demo; generate real keys with crypto.randomBytes(24).toString('base64url')
const keys = [{ id: 'key_1', account: 'acme', scopes: ['reports:read'], hash: sha256(issuedKey) }];
function apiKeyAuth(requiredScope) {
return (req, res, next) => {
const presented = req.get('X-Api-Key');
if (!presented) return res.status(401).json({ error: 'Missing X-Api-Key header' });
const hash = sha256(presented);
const key = keys.find((k) => timingSafeEqual(k.hash, hash)); // constant-time comparison
if (!key) return res.status(401).json({ error: 'Invalid API key' });
if (!key.scopes.includes(requiredScope)) return res.status(403).json({ error: `Key lacks scope ${requiredScope}` });
req.account = key.account;
next();
};
}
app.get('/api/reports', apiKeyAuth('reports:read'), (req, res) => res.json({ account: req.account, reports: ['Q3 revenue'] }));
app.delete('/api/reports/q3', apiKeyAuth('reports:write'), (req, res) => res.status(204).end());
app.listen(process.env.PORT ?? 3000);
$ curl http://localhost:3000/api/reports
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
{
"error": "Missing X-Api-Key header"
}
$ curl http://localhost:3000/api/reports -H 'X-Api-Key: lf_live_guess'
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
{
"error": "Invalid API key"
}
$ curl http://localhost:3000/api/reports -H 'X-Api-Key: lf_live_k3yk3yk3yk3yk3yk3yk3yk3y'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"account": "acme",
"reports": [
"Q3 revenue"
]
}
$ curl -X DELETE http://localhost:3000/api/reports/q3 -H 'X-Api-Key: lf_live_k3yk3yk3yk3yk3yk3yk3yk3y'
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
{
"error": "Key lacks scope reports:write"
}- Hash keys at rest. If your database leaks, hashed keys can't be used. Show the full key once; afterwards show only a prefix (
lf_live_k3y…). - Scopes limit what a key can do: this key can read reports but got 403 when deleting.
- Prefixes like
lf_live_/lf_test_tell humans and secret scanners what a key is – GitHub automatically detects leaked keys with known prefixes. - Let customers create several keys and revoke them individually; log the last use of each.
OAuth 2.0 in plain words
OAuth 2.0 lets an app get a limited access token without ever seeing the user's password. An authorisation server (Google, Salesforce, Okta, Auth0, Keycloak…) issues tokens; your API (the resource server) checks them.
Authorization Code flow with PKCE (user logs in)
- Redirectthe app sends the user to the authorisation server's login page with a code challenge
- Consentthe user logs in and approves the requested scopes
- Codethe server redirects back with a one-time authorisation code
- Tokenthe app exchanges code + verifier for an access token (and refresh token)
- Callthe app calls the API with Authorization: Bearer <access token>
| Flow | Use when |
|---|---|
| Authorization Code + PKCE | a user logs in – web apps, SPAs, mobile apps |
| Client Credentials | machine to machine, no user (a nightly sync job) |
| Refresh Token | getting a new access token without logging in again |
| Device Code | TVs and CLIs without a browser |
| Implicit, Password | legacy – don't use for new apps |
OpenID Connect is a layer on top of OAuth 2.0 that adds an ID token describing who the user is – that's what "Log in with Google" uses.
Choosing
- Server-to-server integration: API keys with scopes, or OAuth Client Credentials.
- Your own web or mobile app's users: Bearer tokens (often JWT) or secure cookies after login.
- Third parties acting for your users, or enterprise SSO: OAuth 2.0 / OIDC via a proven provider.
- Always: HTTPS only, short-lived tokens, and authorisation checks on every request.
Practice
Try it yourself
A mobile app needs to call your API for its logged-in users. A teammate suggests embedding one API key in the app. What's wrong, and what should you do?
Show answer
Anyone can extract a key from an app package, and one shared key can't tell users apart or be revoked per user. Have users log in and receive short-lived per-user tokens (OAuth 2.0 Authorization Code + PKCE, or your own login issuing access and refresh tokens).
Quick check
Authentication vs authorisation?
Who you are vs what you're allowed to do.
How should API keys be stored on the server?
As hashes, compared in constant time.
Which OAuth flow fits a machine-to-machine job?
Client Credentials.
Summary
- API keys identify apps; bearer tokens or cookies identify users; OAuth 2.0 delegates access safely.
- Hash keys, add scopes and prefixes, and support revocation.
- Use Authorization Code + PKCE for users and Client Credentials for machines.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.