API Key 是識別應用程式的秘密字串,指南整理安全管理方法
An API Key Is a Secret That Identifies Your App
API Key 是隨應用程式請求傳送、用來識別呼叫端的秘密字串,任何持有者都可使用,因此單靠它只能提供較弱的身份驗證。指南建議透過 HTTPS 將它放在 Authorization 標頭,並存於伺服器環境變數或密鑰管理服務,避免放進程式碼、用戶端應用程式或 URL。輪換時先建立並部署新 Key,再撤銷舊 Key;外洩後還要查閲請求記錄並修補外洩原因。
An API key is a secret string that an app sends with every request so the server can tell which client is calling. Anyone who holds the string can use it: RFC 6750 describes this property for bearer tokens, where any party in possession of the token can use it without proving anything else.[1] The short rule: treat it like a password for your app, send it in a request header, keep it out of source code and rotate it on a schedule. The rest of this guide covers what a key proves, where to put it in a request, how to store it, and what to do when one leaks.
What an API key is, and what it is not
Stripe calls its secret keys a form of account credentials, like a username and password.[5] That is the right mental model, with one twist. A password belongs to a person. An API key belongs to a program, a project or an account, and it travels with every call that program makes.
OWASP gives two reasons a service issues keys. Public services without access control risk being farmed, which leads to excessive bills for bandwidth or compute. Keys also let organizations monetize an API, because clients get access in line with a purchased plan instead of being blocked at high call rates.[2] Neither reason is "prove this is a trustworthy person."
The word "key" hides four separate jobs. Keep them apart and the error codes further down are easier to read.
| Job | Question the server asks | What the key does | Failure response |
|---|
| Identification | Which client is this? | Ties the call to an account or a purchased access plan[2] | Key missing or unknown |
| Authentication | Is the secret real and still valid? | Proves the caller holds a key the server issued | 401: wrong or no authentication[2] |
| Authorization | Is this key allowed to do this? | Depends on the permissions attached to the key, such as Stripe's restricted keys[5] | 403: authenticated, but no permission[2] |
| Rate limiting | Is this client calling too fast? | Lets the server reject callers that send requests too quickly | 429 Too Many Requests[2] |
A key authenticates weakly. Possession is the only proof, so a leaked key works for whoever finds it. OWASP says API keys issued to third-party clients are relatively easy to compromise, and tells teams not to rely exclusively on them to protect sensitive, critical or high-value resources.[2] For anything that moves money or exposes customer data, add scoped permissions and short lifetimes on top.
API key vs OAuth access token
An OAuth 2.0 access token is issued by an authorization server and represents a grant's scope, duration and other attributes.[1] RFC 6750 recommends short-lived bearer tokens of one hour or less, because that reduces the impact of a leak.[1] An API key is whatever your vendor's dashboard hands you. Lifetimes are vendor-specific: OpenAI, for one, recommends setting an expiration date when you create a project key.[6] A key with no expiry stays valid until you revoke it, so the leak window can be long, which is why rotation matters below.
How to send an API key in a request
RFC 6750 defines three ways to send a bearer token: the Authorization header, a form-encoded body parameter and a URI query parameter. Clients must not use more than one in the same request.[1] The spec is clear about which one to pick: clients SHOULD use the Authorization header with the Bearer scheme, and resource servers MUST support it.[1] One scoping note: RFC 6750 covers OAuth bearer tokens and does not mention API keys by name. It applies here because a key sent in a header behaves like a bearer token, but your vendor's documentation has the final word. This is the RFC's own example, with the token swapped for a placeholder:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer YOUR_API_KEY
In a shell, set the key as a variable for the current session and let the command read it. Stripe's docs use exactly this pattern for code examples, and note that the variable clears when you close the terminal.[5] OpenAI's production guide shows the same header shape, Authorization: Bearer $OPENAI_API_KEY.[6] The host below is a placeholder.
export API_KEY=YOUR_API_KEY
curl https://api.example.com/v1/things \
-H "Authorization: Bearer $API_KEY"
The same call from Node, reading the key from the environment and refusing to run without it:
const apiKey = process.env.API_KEY
if (!apiKey) throw new Error('API_KEY is not set')
const res = await fetch('https://api.example.com/v1/things', {
headers: { Authorization: 'Bearer ' + apiKey },
})
if (!res.ok) throw new Error('Request failed: ' + res.status)
console.log(await res.json())
Header vs query string vs body
| Method | Looks like | RFC 6750 verdict | Why |
|---|
| Authorization header | Authorization: Bearer YOUR_API_KEY | Clients SHOULD use it; servers MUST support it[1] | A header is not part of the URL; RFC 6750 warns that URLs can end up in browser history and server logs[1] |
| Form-encoded body | access_token=YOUR_API_KEY | SHOULD NOT be used except where browsers cannot reach the header; never with GET[1] | Strict conditions: single-part body, ASCII only, form content type |
| Query string | ?access_token=YOUR_API_KEY | SHOULD NOT be used unless the header and body are both impossible[1] | The URL is likely to be logged[1] |
The query string is the one to avoid. RFC 6750 says the method documents current use and is not recommended because of its security deficiencies.[1] OWASP's REST cheat sheet agrees and marks this shape as "NOT OK" because the key is in the URL:[2]
https://example.com/controller/123/action?apiKey=YOUR_API_KEY
OWASP's reasoning is that passwords, security tokens and API keys in a URL can be captured in web server logs, which makes those logs valuable to an attacker. Its rule: in GET requests, send sensitive data in an HTTP header; in POST and PUT requests, use the body or a header.[2]
One caveat. Bearer is the scheme RFC 6750 registers, but an API is free to require something else, such as a custom header. MDN lists several other schemes that ride in the same Authorization header, including Basic, Digest and AWS4-HMAC-SHA256.[7] The vendor's documentation decides the exact header name and format. If you use Basic, remember that base64 is reversible, so it offers no cryptographic security on its own.[7]
Whatever the method, use HTTPS. OWASP says secure REST services must only provide HTTPS endpoints, which protects credentials such as API keys in transit.[2] RFC 6750 makes TLS mandatory for bearer token use.[1]
Where an API key is allowed to live
Stripe's guidance states the rule clearly, and OpenAI's production guide says the same: avoid exposing keys in code or public repositories.[6] Under Stripe's rules, secret keys must stay in your server environment. Never put them in source code, because bad actors continuously scan public repositories, and even private repositories can be exposed through development environments.[5] Never embed them in applications either, since unauthorized parties can unpack an app to search for embedded keys. For client-side use, Stripe tells you to embed its publishable keys instead.[5]
| Place | Verdict | Reason |
|---|
| Source code, committed to Git | Never | Public repositories are scanned continuously; private ones leak through developer environments[5] |
| Browser or mobile app | Never for secret keys | Apps can be unpacked to find embedded keys[5] |
| Environment variable on the server | Acceptable | Stripe names it as the fallback when no vault exists;[5] OpenAI lists environment variables or a secret management service[6] |
| Secrets vault or manager | Preferred | Keeps the value out of source, CI config and developer environments, and adds an audit log of every access[5] |
| Docker ENV or ARG | Never | They can easily leak with the container definitions[3] |
| Email, chat, support tickets | Never | Share keys through secret-management tools; Stripe never asks for your secret key[5] |
Environment variables have their own trap. Stripe warns against exposing them to users, for example by printing them on error pages or by leaving diagnostic modes open to a broad audience.[5] A vault, in Stripe's description, stores credentials separately from your code and supplies them at runtime; your code refers to the key by name, and you can revoke access instantly without redeploying.[5]
Stripe also recommends a pre-commit hook that rejects commits containing keys a secret scanner detects. If you find a key in code, assume it is already exposed and compromised.[5]
Limit what a key can do
A key that can do everything makes every leak a worst-case leak. The providers' docs point the same way on narrowing it:
Use restricted keys with specific privileges, not one broad secret key. Stripe's example is an invoicing system that can manage invoices and nothing else, or a read-only key for a third party that monitors disputes.[5]
Restrict by network when your service sends requests from stable IP addresses. Stripe can block requests made with your keys from anywhere else.[5]
Give each environment its own project. OpenAI suggests separate staging and production projects, with user access to production limited and custom rate and spend limits per project.[6]
Set spend alerts, and treat hard spend limits with care. OpenAI notes that a hard limit stops affected API traffic when tracked spend reaches it, so read the guide before enabling one in production.[6]
Rotate keys before you have to
OWASP's argument for rotation is simple: rotate regularly so that stolen credentials work only for a short time. It adds that the right lifetime depends on what the secret protects, anywhere from minutes to years.[3]
Stripe adds that practicing rotation confirms you know where each key is used and that your team can replace one on short notice.[5]
OpenAI documents the sequence that avoids downtime. Set an expiration date when you create a project key, and before it expires: create a replacement, update your applications to use it, then revoke the old key once you have verified the replacement works.[6] Revoke last, not first. Revoking first turns a routine rotation into an outage.
What to do when an API key leaks
Stripe draws a useful line. Exposure means the key became visible somewhere it should not have, such as a public repository, a log file or an email. Compromise means there is evidence of unauthorized use.[5] Its instruction covers both: if a key is exposed or compromised, rotate it immediately even if you are not sure anyone saw it.[5] The response, in order:
Create a replacement key and revoke the leaked one. GitHub's guidance on a secret scanning alert is to rotate the affected credential immediately.[4]
Deploy the new key through your vault or environment configuration, so every service that used the old key switches over. Revoking before the new key is live can cause downtime. For a leaked key that trade is usually worth it, but that is our judgment, not a vendor rule.
Do not spend the first hour rewriting Git history. GitHub says removing a secret from history is time-intensive and often unnecessary if you have already revoked the credential.[4]
Read the request logs for the key's usage window to find calls you did not make. Stripe recommends auditing request logs to spot misused keys.[5]
Find the cause: a committed file, a log line, a chat message, a client bundle. Fix that path, or the next key leaks the same way.
Detection helps but is not a plan. GitHub's secret scanning covers the entire Git history on all branches, plus issue and pull request text, discussions, wikis and secret gists. It runs automatically and free on public repositories, and organization-owned private repositories need GitHub Secret Protection.[4] For partner providers, GitHub notifies the provider so it can act, for example by revoking the credential.[4] Stripe sometimes deactivates a detected key proactively but does not guarantee detection of every exposed key.[5] For setup details on the newest layer of scanning, see WOWHOW's guide to Copilot secret scanning.
Watch usage as well. OWASP says to check whether the caller comes from an expected IP with an expected user agent, and if not, to alert and assume the secret is compromised.[3]
What breaks: errors and fixes
When a key-authenticated call fails, the status code usually says which of the three jobs went wrong. RFC 6750 maps its bearer error codes to statuses, and OWASP and MDN describe the 401 and 403 split.[1][2][8] For a deeper treatment of the two status codes, read WOWHOW's 401 vs 403 explainer.
| Symptom | Likely cause | Fix |
|---|
| 400, invalid_request | The request is malformed, repeats a parameter or sends the token by more than one method[1] | Send the key in one place only, preferably the header |
| 401, no key was sent | The server answers a request without credentials with WWW-Authenticate: Bearer realm="example" and no error code[1] | Add the Authorization header |
| 401, invalid_token | The token is expired, revoked, malformed or otherwise invalid[1] | Issue a new key and check it was copied whole |
| 401 right after a leak | The provider may have deactivated the key after detecting exposure[5] | Rotate, then find the leak |
| 403, insufficient_scope | The credentials are valid but inadequate for this resource[1][8] | Create a key with the permission this call needs |
| 404 where you expect a resource | Servers may return 404 to hide a resource from a caller without adequate privileges[8] | Check the key's permissions before the URL |
| 429 | Too many requests for this key[2] | Back off, or move to a higher plan if the vendor offers one |
The 401 response in the first non-error row looks like this in the RFC:[1]
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"
Quick reference
An API key identifies a calling app and, by itself, authenticates it weakly, because whoever holds the string can use it. Send it in the Authorization header over HTTPS, never in the URL. Keep it on the server, in a vault or an environment variable, and out of source code, client apps and container definitions. Narrow it with restricted permissions, separate projects and IP limits. Rotate on a schedule: create the new key, deploy it, then revoke the old one. When a key leaks, revoke and replace it first, read the logs second, and clean up Git history only if you still need to.
Sources
REST Security Cheat Sheet, OWASP Cheat Sheet Series (accessed November 25, 2026)
Secrets Management Cheat Sheet, OWASP Cheat Sheet Series (accessed November 25, 2026)
Best practices for managing secret API keys, Stripe Documentation (accessed November 25, 2026)
Production best practices, OpenAI API documentation (accessed November 25, 2026)
Authorization header, MDN Web Docs (accessed November 25, 2026)
8. HTTP authentication, MDN Web Docs (accessed November 25, 2026)
Originally published at wowhow.cloud
來源:DEV Community · dev.to