Lesson 1.5 · 5 of 7 · 6 min read · Reviewed 24 Nov 2026
Authentication: API keys and bearer tokens
By the end, you can
- Explain how API keys and bearer tokens authenticate a request.
- Keep keys out of code, logs and browsers, and know what to do when one leaks.
A model API needs to know who is calling, so it can bill the right account and apply the right limits. That is authentication. For most model APIs it is a long secret string sent with every request.
Two common shapes
| Shape | Header | Typical use |
|---|---|---|
| API key | A provider-specific header, for example x-api-key: <key> |
Server-to-server calls to one provider |
| Bearer token | Authorization: Bearer <token> |
OAuth access tokens, many APIs and gateways |
A bearer tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. is named for its rule: whoever bears it is let in. There is no extra check that you are the right person. Both shapes behave like a password, so treat them like one. Always send them over HTTPS so nobody on the network can read them.
API keys are usually long-lived until you revoke them. OAuthOAuth: A standard for granting an application limited access to a user’s account on another service without sharing their password. access tokens usually expire after minutes or hours and are refreshed with a separate token, which limits the damage if one leaks.
Where the key lives
import os
import anthropic
# The SDK reads ANTHROPIC_API_KEY from the environment by default.
client = anthropic.Anthropic()
# Or, explicitly, still from the environment:
key = os.environ["ANTHROPIC_API_KEY"]
| Place | Verdict |
|---|---|
| Hard-coded in source | Never. It ends up in git, screenshots and pastes |
| Environment variable | Good for local work and most deployments |
.env file loaded at start |
Fine locally, if .env is in .gitignore |
| Secret manager (cloud vault, CI secrets) | Best for production: access control, audit log, rotation |
| Browser or mobile app bundle | Never. Anyone can open developer tools and read it |
A worked example: a browser app
You build a chat widget for a website. The tempting shortcut is to call the model API straight from the page’s JavaScript. That puts your key in every visitor’s browser.
Instead, add a small backend:
- The browser sends the user’s message to your endpoint, with the user’s own session cookie.
- Your backend checks who the user is and applies a per-user limit.
- Your backend calls the model API with the key from its environment.
- It returns only the answer to the browser.
The key never leaves the server, and you can cut off one abusive user without rotating anything.
Keep keys out of logs
Logging whole requests is a common way keys leak. RedactRedaction: Removing or masking sensitive data, such as PII or secrets, before it is stored, logged or sent. the Authorization and key headers before logging, and never print os.environ. If you must show a key in a UI, show only the last four characters.
When a key leaks
- Revoke it in the provider console. This is the only step that stops misuse.
- Issue a new key and deploy it through your secret store.
- Check usage for the leak window.
- Clean up: remove it from history, and add a secret scanner to CIContinuous integration (CI): Automatically building and testing code on every change, usually in a hosted pipeline. so it does not happen again.
Common mistakes
- One key shared by every service and developer, so you cannot tell who used what or revoke one without breaking all.
- Giving a key more access than it needs. Use separate keys per environment and per service where the provider allows it.
- Pasting real keys into online tools or chat windows “just to test”. This site’s Playground uses simulated keys such as
sk-ant-sim-demo-0001for that reason.
Key points
- An API key or bearer token is a password for software. Whoever holds it can spend your quota and read what it can read.
- Send it in a header over HTTPS. Load it from an environment variable or a secret manager, never from source code.
- Never ship a provider key to a browser or mobile app. Put a small backend in between that holds the key and checks the user.
- If a key leaks, revoke it first, then rotate it and look at usage. Deleting the commit is not enough.
Load a key safely and redact logs
Read an API key from the environment and log requests without leaking it.
You will have: A script that loads the simulated key from the environment and prints a log line where secret headers show only the last four characters.
Steps
- Read ANTHROPIC_API_KEY with os.environ.get instead of writing it in the code.
- Build the request headers with the key.
- Write redact() so x-api-key and Authorization show "****" plus the last four characters.
- Print the log line and check the full key does not appear in it.
Done when
- The script reports the key was loaded from the environment.
- The log line shows ****0001 and never the full key.
- No key, real or simulated, is written in the source code.
Open in the Playground No API key needed.
Starter code (Python)
import os
# TODO: read the key from the ANTHROPIC_API_KEY environment variable (never hard-code it)
key = ""
print("key loaded from environment:", "yes" if key else "no")
def build_headers(api_key):
return {"content-type": "application/json", "x-api-key": api_key, "anthropic-version": "2023-06-01"}
def redact(headers):
# TODO: return a copy where x-api-key and authorization show only "****" plus the last 4 characters
return dict(headers)
headers = build_headers(key)
log_line = f"POST /v1/messages headers={redact(headers)}"
print("log:", log_line)
# TODO: print whether the full key appears in log_line (it must be False)
Show a solution
import os
# The key comes from the environment (the Playground's Keys & Env panel holds a simulated one).
key = os.environ.get("ANTHROPIC_API_KEY", "")
print("key loaded from environment:", "yes" if key else "no")
def build_headers(api_key):
return {"content-type": "application/json", "x-api-key": api_key, "anthropic-version": "2023-06-01"}
SECRET_HEADERS = {"x-api-key", "authorization"}
def redact(headers):
"""Return a copy that is safe to log: secrets show only their last four characters."""
return {k: ("****" + v[-4:] if k.lower() in SECRET_HEADERS and v else v) for k, v in headers.items()}
headers = build_headers(key)
log_line = f"POST /v1/messages headers={redact(headers)}"
print("log:", log_line)
print("key in log:", key in log_line)
print("bearer form:", redact({"Authorization": "Bearer " + key}))