Explain it simply
Explain it simply
Authentication answers one question: who are you? Authorization answers another: what are you allowed to do? A hotel key card is a good picture. When the front desk gives you a card, it has already checked who you are (authentication). The card then opens your room, the gym and the lift, but not other guests' rooms (authorization). An API works the same way, except that the card is a string of characters you attach to every request. Whoever holds the string is treated as you, which is why guarding it matters as much as guarding a password.
Problem → Why → Solution
The problem: a key pasted into code reaches everyone
A team ships a mobile app that calls a paid weather API. To make it work quickly, the developer pastes the API key into the app's JavaScript and commits the file. A week later the bill is ten times higher than expected. Anyone can open the network tab, copy the key and run their own projects on your account. The key is also in the git history, so even after the line is deleted, everyone who has the repository still has the key.
The second trouble is vague errors. Calling without credentials, with a wrong key, and with a valid key that lacks permission all fail, but for three different reasons and with two different status codes. Mixing them up makes debugging slow.
// BAD: a secret baked into code that ships to users and lives in git
const API_KEY = "key_live_EXAMPLE_DO_NOT_USE";
// api.example.com is a placeholder host used for illustration only
const res = await fetch("https://api.example.com/v1/forecast?city=Yangon", {
headers: { Authorization: "Bearer " + API_KEY },
});Why is this so dangerous?
Code that ships to a browser or a phone can be read by anyone, and git remembers every line ever committed. A credential is only as safe as the most public place it has ever been written. Credentials must therefore come from the environment at run time, live on a server you control, and be scoped so that a leak does only limited damage.
Core concept: who you are, then what you may do
Authentication (authn) proves identity: this request comes from application X or from user Y. Authorization (authz) decides what that identity may do: may it read reports, may it delete them. APIs report the two failures differently. 401 Unauthorized, despite its name, means authentication failed or is missing: no credentials, an expired token, a wrong key. A 401 should come with a WWW-Authenticate header naming the scheme the server expects. 403 Forbidden means the server knows who you are and refuses anyway: the credentials are valid but lack permission. Some APIs answer 404 instead of 403 to hide that a resource exists.
There are four common kinds of credential. An API key is a long random string that identifies the calling application or project. It is simple, usually does not expire on its own, and fits server-to-server calls. A bearer token is any token sent as Authorization: Bearer <token> (RFC 6750); whoever holds (bears) it is accepted. A JWT (JSON Web Token) is one popular token format that carries signed claims, such as a user id and an expiry time, and is typically short-lived. OAuth 2.0 is a framework (RFC 6749) in which a user lets an application act on their behalf with limited permissions, without sharing their password; the result is an access token with scopes, often with a refresh token to obtain new ones. A session cookie works differently: after login the server stores a session and gives the browser a cookie, which the browser sends automatically. That suits websites but needs protection against CSRF.
In every case the credential is just text attached to the request, nearly always in the Authorization header (or Cookie for sessions). Some APIs expect an API key in a custom header such as X-API-Key, and a few accept it in the query string, which you should avoid because URLs get logged. Always use HTTPS: on plain HTTP anyone on the path can read the header.
Treat a secret as something that must never appear in client-side code (browser JavaScript, mobile apps), in git, in logs, in URLs, in chat messages or in screenshots. During development keep secrets in a .env file that is listed in .gitignore, and commit a .env.example with the names but no values. Load them into environment variables and read them with process.env.NAME; in production use the secret store of your hosting platform or cloud. If an API has to be used from a browser, call your own backend, which holds the key and calls the provider on your behalf.
Plan for leaks, because eventually one happens. Rotation means replacing a credential on a schedule or after an incident: create the new key, deploy it, check that traffic works, then revoke the old one. Least privilege means each credential gets only the permissions it needs: a read-only key for a dashboard, a separate key per service and per environment, short-lived tokens where possible. With these habits, a key leaked from a test environment cannot touch production data.
- Request arrives with a credential
- Authenticate: who is this?
- Authorize: may they do this?
- Allowed: 200, otherwise 401 or 403
401 means "I do not know who you are"; 403 means "I know, and the answer is no".
General pattern: headers that carry a credential
Authorization: <scheme> <credential>
Authorization: Bearer <access-token>
X-API-Key: <api-key> (the header name is provider-specific)
Cookie: session=<session-id> (sent by the browser automatically)The Authorization header carries a scheme (Bearer, Basic) and a credential separated by one space. For API keys the header name depends on the provider, so check the documentation. You do not set Cookie yourself; the browser sends it.
Example: seeing 401 and 403 for yourself
This mock API has two keys: a read key that may only read reports, and an admin key that may delete them as well. The client calls with no credentials, an unknown key, the read key and the admin key. Look at the results: two kinds of 401 (nothing sent, unknown key), one 403 (a valid key without permission) and the 200 responses. Notice also that the keys are read from environment variables, with fake demo values only as a fallback.
import http from "node:http";
// Fake credentials for this demo only. Real ones come from the environment.
const readKey = process.env.APIGUIDE_DEMO_READ_KEY ?? "read-key-123";
const adminKey = process.env.APIGUIDE_DEMO_ADMIN_KEY ?? "admin-key-456";
const scopesByKey = new Map([
[readKey, ["reports:read"]],
[adminKey, ["reports:read", "reports:write"]],
]);
function send(res, status, payload, extra = {}) {
res.writeHead(status, { "Content-Type": "application/json", ...extra });
res.end(JSON.stringify(payload));
}
// Returns true when the request may continue; otherwise it has already answered.
function authorize(req, res, scope) {
const header = req.headers.authorization ?? "";
const key = header.startsWith("Bearer ") ? header.slice(7) : "";
const scopes = scopesByKey.get(key);
if (!scopes) {
const error = header ? "invalid credentials" : "missing credentials";
send(res, 401, { error }, { "WWW-Authenticate": 'Bearer realm="reports"' });
return false;
}
if (!scopes.includes(scope)) {
send(res, 403, { error: "insufficient scope" });
return false;
}
return true;
}
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/reports") {
if (authorize(req, res, "reports:read")) send(res, 200, { reports: ["Q1", "Q2"] });
} else if (req.method === "DELETE" && req.url === "/reports/7") {
if (authorize(req, res, "reports:write")) send(res, 200, { deleted: 7 });
} else {
send(res, 404, { error: "not_found" });
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
async function call(label, method, path, key) {
const res = await fetch(base + path, {
method,
headers: key ? { Authorization: "Bearer " + key } : {},
});
console.log(label, "->", res.status, JSON.stringify(await res.json()));
const challenge = res.headers.get("www-authenticate");
if (challenge) console.log(" WWW-Authenticate:", challenge);
}
await call("GET /reports, no credentials", "GET", "/reports");
await call("GET /reports, unknown key", "GET", "/reports", "wrong-key");
await call("GET /reports, read-only key", "GET", "/reports", readKey);
await call("DELETE /reports/7, read-only key", "DELETE", "/reports/7", readKey);
await call("DELETE /reports/7, admin key", "DELETE", "/reports/7", adminKey);
server.close();Code breakdown
- Secrets from the environment
const readKey = process.env.APIGUIDE_DEMO_READ_KEY ?? "read-key-123";This is the pattern for reading a secret from process.env. The value after ?? exists only so the demo runs. In a real service a missing variable should stop startup with an error, never fall back to a fake value.
- Key to permissions
[adminKey, ["reports:read", "reports:write"]],Each credential is tied to a list of permissions (scopes). The read key lacks reports:write and so cannot delete, which is least privilege in action.
- Parse the scheme
const key = header.startsWith("Bearer ") ? header.slice(7) : "";The Authorization header starts with "Bearer " followed by the credential. "Bearer " is 7 characters long, so slice(7) keeps only the credential. A wrong scheme leaves key empty and ends in a 401.
- 401: who are you?
if (!scopes) {An unknown key, whether missing or wrong, means the identity is unknown, so the answer is 401. The WWW-Authenticate header tells the client that the Bearer scheme is expected.
- 403: known but not allowed
if (!scopes.includes(scope)) {A known key without the scope gets a 403. Retrying with the same key will not help; the client needs a credential with more permission.
- Client sends the key
headers: key ? { Authorization: "Bearer " + key } : {},The Authorization header is added only when a key exists, so the first call carries no header at all. Sending the key in a header is safer than putting it in the URL.
GET /reports, no credentials -> 401 {"error":"missing credentials"}
WWW-Authenticate: Bearer realm="reports"
GET /reports, unknown key -> 401 {"error":"invalid credentials"}
WWW-Authenticate: Bearer realm="reports"
GET /reports, read-only key -> 200 {"reports":["Q1","Q2"]}
DELETE /reports/7, read-only key -> 403 {"error":"insufficient scope"}
DELETE /reports/7, admin key -> 200 {"deleted":7}The four mechanisms compared
| Mechanism | What it identifies | Typical use |
|---|---|---|
| API key | An application or project | Server-to-server calls, simple data APIs |
| Bearer token (JWT) | A user or client, with claims and an expiry | Your own app's API, mobile and single-page apps |
| OAuth 2.0 access token | A user who granted limited access to an app | "Sign in with...", third-party integrations |
| Session cookie | A logged-in browser session | Traditional websites on your own domain |
Each one has a main risk and a main defence. The table below summarises what you will meet again and again in practice.
| Mechanism | Main risk | Main defence |
|---|---|---|
| API key | Never expires and is easily shared too widely | Rotate, restrict scope or IP where offered, keep it server-side |
| Bearer token (JWT) | A stolen token works until it expires | Short lifetime, HTTPS, never log it |
| OAuth 2.0 | Over-broad scopes, leaked refresh tokens | Request minimal scopes, store refresh tokens securely |
| Session cookie | CSRF | HttpOnly, Secure and SameSite flags plus CSRF tokens |
Handling secrets inside a project
The same layout works in every project. Keep the real token in .env and list that file in .gitignore; the committed .env.example holds names only. With Node 20.6 or newer you can load .env with node --env-file=.env app.mjs, no package needed.
# .gitignore
.env
# .env (never committed; real values live here)
API_TOKEN=paste-your-real-token-here
# .env.example (committed; names only)
API_TOKEN=
# Run with the variables loaded, then call an API with the token
node --env-file=.env app.mjs
curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com/v1/reportsA helper that checks for a missing variable up front saves you from "I got a 401 on the first request and do not know why": the app fails at startup with a clear message. (On Windows, cmd references the variable as %API_TOKEN% and PowerShell as $env:API_TOKEN; the tools lesson covers the Windows quoting differences.)
function requireEnv(name) {
const value = process.env[name];
if (!value) {
throw new Error("Missing environment variable " + name);
}
return value;
}
try {
requireEnv("APIGUIDE_DEMO_TOKEN_THAT_IS_NOT_SET");
} catch (error) {
console.log(error.message);
}In real projects
How teams handle auth in real projects
Leaks are rarely malicious; they are almost always an accidental commit. Automated scanners search public repositories for keys, so a leaked key can be abused quickly, and some providers run secret scanning themselves and revoke leaked keys. Teams add a secret scanner to their CI pipeline and record an owner, a purpose and an expiry date for every key.
In production, secrets live in the hosting platform's secret store or the cloud provider's secret manager and are injected as environment variables when the app starts. Each environment (development, staging, production) has its own keys and each service its own key, so one leak has a limited blast radius. A browser or mobile app that calls your backend instead of the provider directly, with the backend holding the key, is a simple and effective pattern, and the backend can add rate limits and usage controls along the way.
Common mistakes
Common mistakes
1. Putting a secret into front-end or mobile code
Minifying or obfuscating does not help: the JavaScript in a browser and the package of a mobile app can be opened, and the header is visible in the network tab. Anything on the client is knowable by everyone, so keep the secret on the backend.
2. Committing .env and deleting it afterwards
Git remembers every commit, so deleting the file in a later commit leaves it in the history for anyone who clones the repository. If a secret has leaked, do not wait to clean the history: revoke the key at once and issue a new one.
3. Treating 401 and 403 as the same thing
On a 401 you check for a missing, wrong or expired credential and may fetch a new token. On a 403 the identity is already accepted, so retrying is pointless; look at the permissions (scopes) instead. Putting both in the same retry loop wastes time and piles up refusals.
4. Logging the whole Authorization header
Printing every request header while debugging puts the token into log files, monitoring tools and team dashboards. Mask headers such as Authorization, Cookie and X-API-Key before logging them, as you will do yourself in the challenge below.
Best practices
Best practices
- Give each credential only the permissions it needs, and use a read-only key for dashboards.
- Issue separate keys per environment and per service, and rotate them on a schedule.
- Prefer short-lived tokens where you can, so a stolen one works for less time.
- Add secret scanning to CI, and revoke at once whenever you suspect a leak.
Mini challenge
Mini challenge: mask secrets before logging
Write redactHeaders(), which takes a headers object and returns a new copy with the values of Authorization, Proxy-Authorization, Cookie and X-API-Key masked. Only the last four characters of a secret may remain visible.
- Compare header names case-insensitively (both Authorization and authorization must be masked)
- When a scheme such as "Bearer " is present, keep the scheme and mask only the credential (Bearer ****9999)
- If the secret part is 8 characters or shorter, show only **** and no trailing characters
- Do not modify the original object, and leave non-sensitive headers untouched
const SENSITIVE = [
// TODO: authorization, proxy-authorization, cookie, x-api-key (lower case)
];
function mask(value) {
// TODO: keep a leading scheme such as "Bearer " when the value has a space
// TODO: replace the secret part with **** plus its last 4 characters
// (only **** when the secret part has 8 characters or fewer)
}
function redactHeaders(headers) {
// TODO: build a new object, masking the sensitive headers
}
// TODO: print JSON.stringify(redactHeaders({ ... })) for a sample set of headersExpected: The output should be (a single line): {"Accept":"application/json","Authorization":"Bearer ****9999","X-API-Key":"****5555","Cookie":"****7777","Proxy-Authorization":"Basic ****"}
Show hint
Use text.indexOf(" ") to find the scheme; it returns -1 when there is none. Take the last four characters with secret.slice(-4). Check the header name with SENSITIVE.includes(name.toLowerCase()).
Show solution
const SENSITIVE = ["authorization", "proxy-authorization", "cookie", "x-api-key"];
function mask(value) {
const text = String(value);
const space = text.indexOf(" ");
const scheme = space > 0 ? text.slice(0, space + 1) : "";
const secret = text.slice(scheme.length);
return scheme + "****" + (secret.length > 8 ? secret.slice(-4) : "");
}
function redactHeaders(headers) {
const copy = {};
for (const [name, value] of Object.entries(headers)) {
copy[name] = SENSITIVE.includes(name.toLowerCase()) ? mask(value) : value;
}
return copy;
}
const headers = {
Accept: "application/json",
Authorization: "Bearer abc123SECRET9999",
"X-API-Key": "key_live_5555",
Cookie: "session=s3cr3t-value-7777",
"Proxy-Authorization": "Basic abc",
};
console.log(JSON.stringify(redactHeaders(headers)));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Authentication is who you are and authorization is what you may do; 401 means missing or wrong credentials, 403 means a known identity without permission.
- An API key represents an application, a bearer token (JWT) a user or client with an expiry, OAuth 2.0 a user's limited grant, and a session cookie a logged-in browser.
- Keep secrets out of client-side code, git, logs and URLs; store them in .env files and environment variables.
- Rotation and least privilege limit the damage of a leak: give every key only the permissions it needs and replace it on a schedule.