Authentication: API Keys, Basic, Bearer Tokens and OAuth Client Credentials
Authenticate to APIs correctly with API keys, HTTP Basic, Bearer tokens and the OAuth client credentials flow, cache and refresh tokens before they expire, keep secrets out of code, and verify the encoding and the token traffic independently.
In this lesson you will
- Choose among key, Basic, Bearer and OAuth
- Encode a Basic auth header correctly
- Run the client credentials flow
- Cache and refresh tokens
About 28 minutes
Proving who you are to someone else’s server
The shipping API wants to know which customer is asking, so that it can bill them and limit abuse. There are four common ways. An API key is a long random string sent in a header, simple and widely used, and like a password it must be kept secret. HTTP Basic sends a username and password, joined by a colon and encoded in Base64, in the Authorization header. Base64 is an encoding, not encryption: anyone who sees the header can decode it, so Basic is only safe over HTTPS. A Bearer token is a string that the caller presents in the Authorization header, “Bearer abc123”, with the meaning “whoever holds this may act”. And OAuth 2.0 is a framework for obtaining such tokens in a controlled way.
For a server-to-server integration like Noor’s, the relevant OAuth flow is client credentials. The program has a client id and a client secret, issued by the provider. It sends them to the provider’s token endpoint and receives an access token with a lifetime, expires_in, in seconds. It then uses the token as a Bearer token until it is about to expire, and asks for a new one. Short lifetimes limit the damage of a leaked token. A good client caches the token, and refreshes it a little early, 30 seconds before expiry, so a request never travels with a token that dies on the way, and does not request a new token for every call, which would be slow and may be rate limited. Secrets come from the environment, never from the source code.
| Method | Header | Notes |
|---|---|---|
| API key | X-Api-Key: abc | Simple, long-lived secret |
| Basic | Authorization: Basic base64(user:pass) | Only over HTTPS |
| Bearer | Authorization: Bearer token | Token proves access |
| OAuth client credentials | POST /token, then Bearer | Short-lived tokens, refresh |
import json, threading, base64, os, time, urllib.request, urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer
CLIENTS = {"noor-shop": "s3cret-value"}
tokens, token_requests, seen = {}, [0], []
NOW = [1000.0] # a controllable clock, so the lesson needs no waiting
class Provider(BaseHTTPRequestHandler):
def reply(self, code, obj):
b = json.dumps(obj).encode(); self.send_response(code); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
def do_POST(self):
if self.path != "/token": return self.reply(404, {})
form = urllib.parse.parse_qs(self.rfile.read(int(self.headers["Content-Length"])).decode())
if form.get("grant_type") != ["client_credentials"] or CLIENTS.get(form.get("client_id", [""])[0]) != form.get("client_secret", [""])[0]:
return self.reply(401, {"error": "invalid_client"})
token_requests[0] += 1
t = "tok-%d" % token_requests[0]; tokens[t] = NOW[0] + 300
self.reply(200, {"access_token": t, "token_type": "Bearer", "expires_in": 300})
def do_GET(self):
h = self.headers.get("Authorization", ""); seen.append(h.split(" ")[0] if h else "none")
if h.startswith("Basic "):
user, _, pw = base64.b64decode(h[6:]).decode().partition(":")
return self.reply(200 if CLIENTS.get(user) == pw else 401, {"auth": "basic", "user": user})
tok = h[7:] if h.startswith("Bearer ") else ""
if tok in tokens and tokens[tok] > NOW[0]: return self.reply(200, {"auth": "bearer", "token": tok})
self.reply(401, {"error": "invalid_or_expired_token"})
def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), Provider); base = "http://127.0.0.1:%d" % srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
os.environ["SHOP_CLIENT_ID"], os.environ["SHOP_CLIENT_SECRET"] = "noor-shop", "s3cret-value" # normally set outside the program
class Client:
def __init__(self): self.token, self.expires = None, 0
def get_token(self):
if self.token and self.expires - 30 > NOW[0]: return self.token # reuse until 30 s before expiry
body = urllib.parse.urlencode({"grant_type": "client_credentials", "client_id": os.environ["SHOP_CLIENT_ID"], "client_secret": os.environ["SHOP_CLIENT_SECRET"]}).encode()
r = json.loads(urllib.request.urlopen(urllib.request.Request(base + "/token", data=body)).read())
self.token, self.expires = r["access_token"], NOW[0] + r["expires_in"]
return self.token
def call(self):
req = urllib.request.Request(base + "/data", headers={"Authorization": "Bearer " + self.get_token()})
return json.loads(urllib.request.urlopen(req).read())
c = Client()
calls = []
for t in [1000, 1010, 1100, 1269, 1271, 1500, 1700]: # clock readings in seconds
NOW[0] = float(t); calls.append((t, c.call()["token"]))
print("clock -> token used:", calls)
print("token requests for 7 calls:", token_requests[0])
basic = "Basic " + base64.b64encode(b"noor-shop:s3cret-value").decode()
r = json.loads(urllib.request.urlopen(urllib.request.Request(base + "/data", headers={"Authorization": basic})).read())
print("Basic header:", basic, "| server decoded user:", r["user"])
try: urllib.request.urlopen(urllib.request.Request(base + "/data", headers={"Authorization": "Bearer made-up"}))
except urllib.error.HTTPError as e: print("made-up token ->", e.code, json.loads(e.read()))
print("DATA " + json.dumps({"calls": calls, "treq": token_requests[0], "basic": basic}))
srv.shutdown()
clock -> token used: [(1000, 'tok-1'), (1010, 'tok-1'), (1100, 'tok-1'), (1269, 'tok-1'), (1271, 'tok-2'), (1500, 'tok-2'), (1700, 'tok-3')]
token requests for 7 calls: 3
Basic header: Basic bm9vci1zaG9wOnMzY3JldC12YWx1ZQ== | server decoded user: noor-shop
made-up token -> 401 {'error': 'invalid_or_expired_token'}
The simulated provider issues tokens that last 300 seconds, and the client has a clock that the lesson controls so that nothing needs to wait. Seven calls were made at the times 1000, 1010, 1100, 1269, 1271, 1500, 1700 seconds. The first call fetched a token, tok-1. The next three, at 1,010, 1,100 and 1,269 seconds, reused it, because it had more than 30 seconds of life left: the token expires at 1,300, and 1,269 is 31 seconds before. The call at 1,271 was inside the 30-second safety margin, so the client got a new token, tok-2, before the old one could die in transit, and the call at 1,700 needed tok-3. The provider saw exactly 3 token requests for seven API calls, which is what a well-behaved client does. A naive client that asked for a token on every call would have made 7.
The Basic header is the string “Basic bm9vci1zaG9wOnMzY3JldC12YWx1ZQ==”: the user name, a colon and the secret, joined and encoded in Base64. The server decoded it and recognised the user “noor-shop”. Because Base64 is trivially reversible, the same string decodes in any language, so Basic must travel only over HTTPS. A made-up bearer token was refused with 401 and the error “invalid_or_expired_token”. Note that the client read its credentials from environment variables, set here by the lesson only to make the example run: in production they are set by the deployment system and never appear in the code or in logs.
Independent check: the Base64 string was produced a second time by the shell command base64, which printed the same value that Python made, “bm9vci1zaG9wOnMzY3JldC12YWx1ZQ==”. The token behaviour was checked against the server’s own count of how many tokens it issued, three, which is a number that the client cannot influence, and the sequence of tokens matches the expiry arithmetic worked out by hand in the next paragraph.
Check by hand: a token issued at time 1,000 with a lifetime of 300 seconds expires at 1,300, and the client treats it as stale at 1,300 minus 30, which is 1,270. At 1,269 it is still usable, and at 1,271 it is not. The second token was issued at 1,271 and expires at 1,571, which covers 1,500 and not 1,700, so a third token is needed.
Anyone who sees an Authorization: Basic header can read the password. Only send credentials over HTTPS, and never log full Authorization headers.
Renew a token a little before it expires, and reuse it for all calls. Asking for a new token on every call is slow and can hit rate limits.
Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. Real OAuth providers have their own endpoints, scopes and error formats, and other flows for user logins. Read the provider’s documentation and the OAuth 2.0 specifications.
Practice
Make the client retry once with a fresh token when the server answers 401. Add a scope parameter to the token request. Write a function that redacts the Authorization header from a request log.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is Base64?
- Encryption
- A hash
- A signature
- An encoding that anyone can reverse
Basic auth needs HTTPS.
What does the client credentials flow produce?
- A password
- A cookie
- A short-lived access token
- A certificate
Use it as a Bearer token.
Why refresh a token 30 seconds before expiry?
- To make it longer
- To change the secret
- So it does not expire during a request
- It is required by HTTP
A safety margin.
Where should a client secret come from?
- The source code
- The environment or a secrets manager
- A web page
- A comment
Never from code.
Why count the token requests?
- To increase the limit
- A well-behaved client reuses its token
- To debug HTTP
- It is required
3 requests for 7 calls.
Summary
- Keys, Basic, Bearer tokens and OAuth are common ways to authenticate.
- Base64 is an encoding, not protection: use HTTPS.
- Cache tokens and refresh them before they expire.
- Secrets belong in the environment, not in code.
Questions
Which method is best?
It depends on the provider. API keys are simplest, and OAuth is preferred where tokens, scopes and short lifetimes matter. Use what the documentation requires.
What are scopes?
Limits on what a token may do, such as read-only access. Request the least that you need.
What if my key leaks?
Revoke it at once in the provider's dashboard, create a new one, find out how it leaked, and check the logs for misuse.
