Computing Foundations › APIs and the Web › Day 25

Day 25: API Authentication: Keys, Tokens, and OAuth

Day 25 of 365 — API Authentication: Keys, Tokens, and OAuth

After this lesson you will be able to authenticate to any API using the scheme it expects — API key, bearer token, Basic auth, or OAuth 2.0 — and keep your credentials out of your code and git so a leaked key never costs you money.

Course
Computing Foundations
Category
APIs and the Web
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-025-api-authentication-keys-tokens-and-oauth

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/computing-foundations/day-025-api-authentication-keys-tokens-and-oauth
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language


Historical background

Diagram: the progression from shared passwords to delegated authorization


What it is — and what it is not

Diagram: authentication compared with authorization

Authentication is:

It is not:


Why it was created and what problems it solves


How it works

Diagram: a request carrying different credential types to a server that checks them

The common schemes

Diagram: API keys, bearer tokens and Basic auth compared

Diagram: sending a key in a header compared with putting it in the URL

API key in a header. The API issues a key; you attach it to a header the API names, commonly X-API-Key:

curl -H "X-API-Key: key-example-abc123" https://api.example.com/v1/data

Bearer token. Sent in the standard Authorization header:

curl -H "Authorization: Bearer token-example-123" https://api.example.com/v1/data

Basic auth. Username and password, joined with a colon and base64-encoded:

curl -u user:pass https://api.example.com/v1/data
# produces: Authorization: Basic dXNlcjpwYXNz

OAuth 2.0, as a story

Flowchart: the OAuth authorization-code flow — user to app to auth server to consent to token to API

Four players: you (the resource owner), the app (the client), the authorization server (the provider’s login and consent service), and the API (holding your data).

  1. The app sends you to the provider. You land on the provider’s own page, not the app’s.

  2. You log in and consent. The provider shows exactly what is being asked for — “read your photos” — and you approve or refuse. Your password is typed into the provider’s page, which the app never sees.

  3. The provider hands the app an authorization code, via a redirect back. This is not yet a usable credential; it is a one-time voucher.

  4. The app exchanges the code plus its own client secret for an access token, app-to-server, out of your browser’s view.

  5. The app calls the API with that token as a bearer token, and gets your photos — only your photos, only within the scope you granted.

Handling secrets safely

Diagram: how a secret reaches a program without entering the repository

export DEMO_TOKEN="token-example-123"
curl -H "Authorization: Bearer $DEMO_TOKEN" https://api.example.com/v1/data

A note on rate limiting


An everyday analogy

Diagram: how to evaluate the scopes an application requests

Different ways of getting into a building.

The buildingThe scheme
Your own name and password at receptionBasic auth
A staff badge issued to youAn API key
A visitor pass anyone holding may useA bearer token
Letting a courier collect one parcel for youOAuth delegation
”Parcels only, third floor, today”Scopes
A pass that expires at 5pmAccess token lifetime
Cancelling a lost badgeRevocation

Examples in practice

Diagram: base64 encoding compared with encryption


Implications: security, privacy, performance, scalability, and cost

Diagram: the response procedure when a credential is exposed


Alternatives: free, open source, and commercial

Diagram: the checks to make before using a new API credential

ApproachTypeWhere it fits
API key in a headerThe common defaultServer-to-server, single account
Bearer tokenThe modern defaultAlmost everything, including model APIs
Basic authBuilt into HTTPInternal tools, behind TLS, where simplicity wins
OAuth 2.0Free, open standardActing on a user’s behalf at another service
mTLSFree, open standardBoth sides prove identity; internal service meshes
Cloud secret managersCommercial, free tiersStorage, rotation and audit once more than one machine needs a key
git-secrets, gitleaksFree, open sourceCatching a key before it is committed

TermWhat it actually is
AuthenticationProving which account this is
AuthorizationDeciding what that account may do
API keyA long-lived secret identifying an account
Bearer tokenA credential whose possession is the authorisation
ScopeThe specific permissions a token carries
Refresh tokenA credential used to mint new access tokens
RotationReplacing a credential on purpose, before you must

When to use it — and when not to

Diagram: unsafe and safe credential handling habits


The AI connection

Diagram: access tokens compared with refresh tokens


Knowledge check

quiz:
  question: "An API accepts its key either as a query parameter or in a header, and both work identically. Why prefer the header?"
  options:
    - "Query strings are recorded in access logs, browser history and Referer headers, where headers are not"
    - "Headers are encrypted by TLS while query strings are sent in plaintext"
    - "Query parameters have a length limit that keys frequently exceed"
    - "Headers are validated by the server before the query string is parsed"
  answer_index: 0
  explanation: "TLS encrypts the whole request, URL included, so transport is not the difference. The difference is what gets written down: URLs are logged by proxies and servers, kept in history, and forwarded in Referer headers, while headers are not recorded by default."

Hands-on exercise

Authenticate three ways, then prove base64 is not a secret. Worked through fully in the Day 25 lab directory.

What you are doingCommand
Call without a credentialcurl -i https://httpbin.org/bearer
Send a bearer tokencurl -i -H "Authorization: Bearer token-example-123" https://httpbin.org/bearer
Send Basic authcurl -i -u user:pass https://httpbin.org/basic-auth/user/pass
Decode what Basic sentecho -n 'user:pass' | base64 then base64 -d it back
Read the key from the environmentexport DEMO_TOKEN=token-example-123 then use $DEMO_TOKEN
Confirm it is not in your sourcegrep -r "token-example" . --exclude-dir=.git

Expected output

HTTP/1.1 401 UNAUTHORIZED
HTTP/1.1 200 OK
{"authenticated": true, "token": "token-example-123"}
dXNlcjpwYXNz
user:pass

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. What is the difference between authentication and authorization?

  1. Authentication encrypts the request; authorization decrypts it
  2. Authentication is for users; authorization is only for machines
  3. They are two words for the same identity check
  4. Authentication proves who you are; authorization decides what you are allowed to do
Show answer

Answer: D. Authentication proves who you are; authorization decides what you are allowed to do

Authentication answers "who are you" and fails with 401; authorization answers "may you do this" and fails with 403. They are separate steps, and confusing them leads to fixing the wrong problem.

Q2. Which HTTP status code means the server does not recognize your credential (authentication failed)?

  1. 401 Unauthorized
  2. 404 Not Found
  3. 403 Forbidden
  4. 429 Too Many Requests
Show answer

Answer: A. 401 Unauthorized

401 Unauthorized signals a missing or invalid credential — an authentication failure. 403 Forbidden means you are authenticated but lack permission (an authorization failure), which is a different fix.

Q3. How is a bearer token sent in an HTTP request?

  1. In the URL as ?token=...
  2. In the Authorization header as a Bearer token
  3. As a base64-encoded username and password
  4. In a cookie that the browser sets automatically for you
Show answer

Answer: B. In the Authorization header as a Bearer token

A bearer token rides in the standard Authorization header with the scheme name Bearer. This is the format the great majority of modern APIs, including hosted model APIs, expect.

Q4. Why is Basic auth unsafe over plain HTTP?

  1. The server refuses Basic auth unless a key is also supplied
  2. Basic auth sends the password as an image that can be screenshotted
  3. Base64 encoding is reversible with no key, so anyone on the network can read the password
  4. Basic auth works only with usernames longer than 16 characters
Show answer

Answer: C. Base64 encoding is reversible with no key, so anyone on the network can read the password

Basic auth base64-encodes user:pass, and base64 is encoding, not encryption — dXNlcjpwYXNz decodes straight back to user:pass. Only the TLS in HTTPS actually protects it in transit.

Q5. Why is putting an API key in a URL query string worse than putting it in a header?

  1. Query strings can only hold 8 characters
  2. Headers are automatically encrypted while query strings are not
  3. A key in a header is ignored by most servers
  4. URLs land in logs, history, and caches, so the key leaks
Show answer

Answer: D. URLs land in logs, history, and caches, so the key leaks

A query string is part of the URL, and URLs get logged, cached, and stored in history. A header is far less likely to be recorded by accident, so the same secret is safer in a header.

Q6. In the OAuth 2.0 authorization-code flow, where does the user type their password?

  1. Into the provider's own authorization server page — the app never sees it
  2. Into the third-party app, which forwards it to the provider
  3. Into the API request as a Basic auth header
  4. Nowhere; OAuth does not use passwords at all
Show answer

Answer: A. Into the provider's own authorization server page — the app never sees it

The whole point of OAuth is delegation without disclosure: the user logs in on the provider's own consent page, and the app receives a scoped access token instead of ever seeing the password.

Q7. What is the difference between an access token and a refresh token?

  1. An access token is public; a refresh token is secret
  2. An access token is short-lived; a refresh token gets new ones
  3. They are identical but issued by different servers
  4. An access token is for reading and a refresh token is for writing
Show answer

Answer: B. An access token is short-lived; a refresh token gets new ones

Access tokens are deliberately short-lived so a leaked one expires quickly; a refresh token lives longer and is used only to mint new access tokens without making the user log in again, which is why it is guarded most carefully.

Q8. You discover an API key was pushed to a public repository ten minutes ago. What is the right first response?

  1. Delete the commit, since that removes the key from history
  2. Do nothing until the monthly bill arrives to confirm misuse
  3. Revoke the key at the provider immediately and issue a new one
  4. Rename the variable so bots cannot find it
Show answer

Answer: C. Revoke the key at the provider immediately and issue a new one

The instant a key touches a public place, treat it as burned: revoke it at the provider and issue a replacement. Deleting the commit does not help — automated scanners find keys within minutes, and the key may already be copied elsewhere.

Glossary

authentication
The process by which a server verifies who is making a request, usually by checking a secret credential the caller presents; failing it returns HTTP 401.
authorization
The process of deciding what an already-identified caller is permitted to do; failing it returns HTTP 403, distinct from an authentication failure.
API key
A long random string an API issues to your account, attached to each request (usually in a header) to identify and authenticate the caller.
bearer token
A credential sent in the standard Authorization header as "Bearer <token>"; possession alone grants access, so it must be guarded like cash.
Basic auth
An HTTP authentication scheme that sends a username and password joined by a colon and base64-encoded in the Authorization header; safe only over TLS.
OAuth
An open standard (OAuth 2.0, RFC 6749) that lets an application act on a user's behalf at another service using a scoped, revocable token, without ever seeing the user's password.
access token
A short-lived credential, obtained through OAuth, that an app sends as a bearer token on each API call; it expires quickly to limit the damage from a leak.
refresh token
A longer-lived OAuth credential used only to obtain new access tokens when they expire, so the user need not log in again; the more sensitive of the two tokens.
scope
A named permission an OAuth token is limited to (such as read photos but not delete them), shown on the consent screen so the user can approve or refuse it.
secret
Any credential — API key, token, or password — that grants access and must be kept out of code and version control; equivalent to a password in the harm a leak causes.
least privilege
The practice of giving a credential the narrowest access that still does the job (read-only, one project, limited spend) so that a leak has the smallest possible blast radius.
base64
A reversible text encoding with no key, used to package binary or colon-separated data for transport; it hides nothing on its own, which is why Basic auth needs TLS.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.