API keys are the simplest way to authenticate to an API, which is exactly why they are everywhere and why they leak so often. A key is a long string that grants access to whoever presents it. It is created in seconds, pasted into code, shared in chat, embedded in mobile apps and forgotten; many keys never expire, carry more permission than needed and cannot be traced to an owner. This guide covers the full lifecycle, from deciding whether to use a key at all to creating, scoping, storing, using, monitoring, rotating and retiring it, for keys you consume and keys you issue. It is written for platform, application security and secrets management teams, and for API product owners who issue keys to customers.
Key takeaways
- An API key is a bearer credential. Possession equals access, so treat every key as the password of a non-human identity.
- Prefer something stronger. OAuth client credentials with short-lived tokens, workload identity federation or mTLS beat static keys; Google and AWS both advise against using API keys alone to control access.
- Every key needs five things. An owner, a narrow scope, restrictions on where it can be used, an expiry or review date, and a home in a secrets manager.
- A key's risk can change without anyone touching it. Google API keys treated as public identifiers gained access to Gemini when that API was enabled on their projects.
- Assume keys will leak. Scan continuously, block secrets at push time, alert on unusual use and practise revoking and replacing a key quickly.
When an API key is the right choice, and when it is not
| Situation | API key suitable? | Better option |
|---|---|---|
| Third-party SaaS API that only offers keys | Yes, with controls | Ask the vendor for OAuth or federation support |
| Identifying a calling project for quota, billing or analytics | Yes | Combine with token-based authentication for sensitive data |
| Service-to-service calls inside your cloud | No | Workload identity, IAM roles, managed identities |
| CI/CD access to cloud providers | No | OIDC workload identity federation |
| Browser or mobile app calling a sensitive API | No, keys in client code are public | User-based OAuth with a backend that adds the credential |
| Partner integrations with sensitive data | Rarely | OAuth with private_key_jwt or mTLS |
The providers say the same. Amazon API Gateway's documentation states: "Don't use API keys for authentication or authorization to control access to your APIs", because a key valid for one API in a usage plan can reach all of them; it points to IAM roles, Lambda authorisers or Cognito instead. Google Cloud separates standard API keys, which associate a request with a project for billing and quota (such a key "doesn't identify a principal"), from authorisation keys bound to a service account, and recommends not using the latter in production but migrating to IAM policies and short-lived service account credentials. RFC 9700 describes the target state for tokens: privileges restricted to the minimum needed and audience-restricted to specific resource servers. See the NHI Authentication Guide and the Workload Identity Federation Guide.
How API keys leak
| Leak path | Example | Primary control |
|---|---|---|
| Source code and repository history | A researcher scanning about 5.6 million public GitLab repositories with TruffleHog reports 17,430 verified live secrets, the oldest valid one committed in 2009 (GitLab Public Repositories Secrets Study 2025) | Push protection, history scanning, rotation |
| Client-side code | Truffle Security found nearly 3,000 live Google API keys in public web pages that could reach Gemini, according to BleepingComputer (Google API Keys Exposure 2026) | API and application restrictions; backend proxy |
| Malicious developer tools | Aikido Security found at least 15 JetBrains Marketplace plugins that sent the AI provider key stored in their settings to a hard-coded server; together installed close to 70,000 times (JetBrains Marketplace AI Plugin Campaign 2026) | Plug-in allowlists; keys kept out of IDE settings |
| Compromise of the key issuer | BeyondTrust said an API key for Remote Support SaaS had been compromised, letting attackers reset local application account passwords (BeyondTrust Breach 2024) | Issuer-side key scoping, monitoring and fast revocation |
| Containers, logs, tickets and chat | Keys in image layers, debug logs, support tickets and chat messages | Log masking; scanning collaboration tools |
| URLs | Keys passed as query parameters end up in logs and history | Send keys in headers only |
These map to OWASP NHI2:2025 Secret Leakage, NHI7:2025 Long-Lived Secrets and NHI9:2025 NHI Reuse. OWASP's NHI7 page cites Datadog's State of the Cloud 2024 finding that 60% of keys across cloud providers are more than a year old. See the Top 10 Secrets Management Mistakes.
The API key lifecycle
The OWASP Secrets Management Cheat Sheet describes a secret lifecycle of creation, rotation, revocation and expiration; the seven stages below expand it for API keys.
1. Request and create
- Create keys through an approved process that records purpose, owner, consuming system, environment and required scope. OWASP recommends storing metadata such as who created it, what it is for, who to contact and when it must be rotated.
- Create keys from service or organisation accounts, not personal accounts that disappear when someone leaves.
- Create one key per consuming application and environment; Google advises isolating keys per team member and application to keep an audit trail and limit impact.
2. Scope and restrict
- Grant the narrowest permissions the provider allows: read-only, specific resources, specific APIs. Stripe, for example, offers restricted keys alongside full secret keys.
- Apply every restriction available. Google Cloud supports API restrictions (which APIs a key can call) and application restrictions (which websites, IP addresses or apps can use it), notes that keys without application restrictions "can be used from anywhere", and recommends setting both.
- Set an expiry. If the provider does not support one, record a review date and enforce it yourself.
3. Store
- Store keys in a secrets manager and inject them at runtime; never commit them to code, images or configuration files. Google's guidance is that the client should pass requests to a server, which adds the credential.
- Restrict who and what can read each key, and audit reads. See the Secrets Management Guide.
4. Use
- Send keys in request headers over TLS, never in URLs. Google warns that query parameters expose keys "to theft through URL scans".
- Keep keys out of application logs and error messages; OWASP says secrets should "never be logged".
- Where the provider allows, exchange the key for short-lived tokens rather than sending it on every request.
5. Monitor
- Scan repositories, CI/CD, containers, collaboration tools and ticketing systems continuously for your key formats.
- Monitor provider-side usage: new source IPs, volume spikes, new endpoints and spend.
6. Rotate
- Rotate on a schedule, immediately after suspected exposure, and when people with access leave (a trigger Stripe's documentation lists).
- Use overlapping keys (create new, deploy, verify, revoke old) to avoid outages, and automate rotation where the provider has an API for it. See the Secrets Rotation Runbook Template.
7. Revoke and retire
- Revoke keys when the integration ends, the owner leaves without handover or the key has been unused for a defined period; Google advises deleting unneeded keys to keep the attack surface small.
- Confirm revocation took effect in provider logs, then remove the key from the secrets manager and inventory.
API keys for AI services and agents
LLM and AI provider keys are now among the most targeted, because they convert directly into compute spend and sometimes into data access. Truffle Security warned, as quoted by BleepingComputer, that an attacker "maxing out API calls could generate thousands of dollars in charges per day on a single victim account". AI agents add a new consumer: an agent that holds a key can be steered into misusing it, and coding agents read the same files and environment variables where keys are left.
- Re-assess keys when APIs change: check which APIs are enabled on each project, since enabling an AI API can widen what existing keys reach. Google says new AI Studio keys will default to Gemini-only scope.
- Give agents their own keys: one key per agent, scoped to its tools and with a spend limit, never a developer's personal key.
- Prefer a gateway: let agents call an internal proxy that holds the provider key, so the agent never sees it. See the LLMjacking Guide, the AI Coding Agents Security Guide and the MCP Security Guide.
If you issue API keys to customers or partners
| Design choice | Why it matters | Example in practice |
|---|---|---|
| High entropy with a recognisable prefix and checksum | Scanners can find keys with few false positives | GitHub added identifiable prefixes and a 32-bit checksum to its tokens and expected the prefix alone to cut secret scanning false positives to 0.5% |
| Show the full key once | Limits copies and lets you store only a hash | Stripe displays a live secret key one time when you create it |
| Customer-controlled scope, expiry and IP restrictions | Customers can apply least privilege themselves | Restricted keys and per-key expiry |
| Last-used time and usage per key | Customers can find and delete unused keys | Key list with last activity |
| Secret scanning partnership | Leaked keys are reported and can be revoked automatically | GitHub's partner program sends matches in public repositories and npm packages to a provider endpoint |
| Stronger alternatives on offer | Sensitive customers can avoid static keys | OAuth client credentials, federation or mTLS |
Validate keys at the gateway but still enforce object-level authorisation in the service; OWASP's API Security Top 10 2023 lists Broken Object Level Authorization and Broken Authentication as its first two risks. See the API Security Guide.
Detection and monitoring
| Signal | Source | Response |
|---|---|---|
| Key pattern in a commit or push | Pre-commit hooks, push protection, CI scanning | Block, then rotate if it reached a remote |
| Key found in public code or packages | Provider partner programmes, public scanning | Treat as compromised; revoke immediately |
| Use from a new IP range, country or user agent | Provider usage logs | Verify with the owner; restrict or rotate |
| Spend or volume spike | Billing alerts, quota metrics | Throttle, investigate, rotate |
| Calls to APIs the key has never used | Provider audit logs | Check for scope drift or abuse; add API restrictions |
| Attempts to use a revoked or expired key | Gateway and secrets manager logs | Find the stale copy and the system still holding it |
GitHub's push protection blocks pushes containing supported secrets "before they reach your repository", which is cheaper than any clean-up. OWASP's cheat sheet adds that secrets should be revocable "including the logging of attempt to use a revoked secret", a useful signal that a leaked copy is still in use. See the CI/CD Pipeline Identity Security Guide.
Responding to a leaked key
- Revoke or disable the key immediately. Do not wait to rotate gracefully if the exposure is public; automated scanners find public keys quickly.
- Issue a replacement and update consumers from the secrets manager, not by pasting the new key around.
- Review provider logs for use since the key was exposed, and investigate unfamiliar sources, endpoints and spend.
- Remove the key from where it leaked, including repository history and package versions, but assume copies exist.
- Fix the cause: add scanning or push protection, move the key to a secrets manager, or replace it with a stronger method. Record the incident against the key's owner and metrics.
For issuer-side compromises, BeyondTrust's response, as reported by BleepingComputer, shows the pattern: it "immediately revoked the API key, notified known impacted customers, and suspended those instances the same day".
Framework mapping
An indicative NHI Mgmt Group alignment, checked against the published control lists; CIS references are at control level.
| Lifecycle area | NIST CSF 2.0 | NIST SP 800-53 Rev. 5 | ISO/IEC 27001:2022 Annex A | CIS Controls v8.1 | OWASP NHI Top 10 |
|---|---|---|---|---|---|
| Inventory and ownership | ID.AM-02, ID.AM-08 | CM-8, IA-4 | A.5.9, A.5.16 | 5 | NHI1 |
| Least privilege and restrictions | PR.AA-05 | AC-6, AC-3 | A.5.15, A.8.3 | 6 | NHI5 |
| Secure storage and no embedded keys | PR.AA-01, PR.DS-01 | IA-5(7), SC-28 | A.5.17, A.8.24 | 3, 16 | NHI2 |
| Expiry and rotation | PR.AA-01 | IA-5 | A.5.17 | 5 | NHI7 |
| One key per consumer and environment | PR.AA-05 | IA-4, AC-2 | A.5.16, A.8.31 | 5 | NHI8, NHI9 |
| Leak detection and usage monitoring | DE.CM-03, DE.CM-09 | SI-4, AU-6 | A.8.15, A.8.16 | 8, 16 | NHI2 |
| Leaked-key response | RS.MI-01, RS.MI-02 | IR-4 | A.5.26 | 17 | NHI2 |
Common failure patterns
- "It's only an identifier": keys left in client code because they were considered harmless, until a newly enabled API made them sensitive, as in the Google API Keys Exposure 2026.
- Deleting the commit, not the key: rewriting history while the key stays valid; the GitLab study found a live secret committed in 2009.
- Keys in developer tools: pasting provider keys into IDE plug-in settings, the exact data the JetBrains Marketplace AI Plugin Campaign 2026 exfiltrated.
- One key, many systems: a shared key means a single leak forces a multi-team rotation, so nobody rotates it (OWASP NHI9).
- No owner, no rotation: keys created from personal accounts outlive the person and are never reviewed. See the NHI Ownership Guide.
- Unrestricted keys: no API or application restrictions, so a key for one map widget can call every API on the project from anywhere.
- Revocation never tested: nobody knows which systems will break, so a leaked key stays live while teams negotiate an outage window.
Metrics that show progress
| Metric | What it shows | Target direction |
|---|---|---|
| Keys in inventory with a named owner and purpose | Accountability | Up, towards 100% |
| Keys older than their rotation period | Long-lived secret exposure (NHI7) | Down |
| Keys without API or application restrictions | Blast radius of a leak | Down |
| Integrations moved from keys to federation or short-lived tokens | Progress away from static secrets | Up |
| Secrets blocked at push compared with found after merge | Shift-left effectiveness | Ratio up |
| Median time from leak detection to revocation | Response speed | Down |
| Keys unused for 90 days or more | Dormant attack surface | Down |
See the Identity Security Metrics Guide.
Implementation roadmap
| Phase | Actions | Exit criteria |
|---|---|---|
| First 30 days | Turn on secret scanning and push protection for all repositories; inventory keys for your top cloud and AI providers; revoke unused and unowned keys; add restrictions to every unrestricted key | Scanning live everywhere; no unrestricted production keys |
| Days 31 to 90 | Move keys into a secrets manager with runtime injection; assign owners; set expiry or review dates; write and rehearse the leaked-key runbook; add spend and usage alerts | All production keys vaulted and owned; one rehearsal completed |
| Days 91 to 180 | Replace keys with workload identity federation or OAuth where providers support it; automate rotation; give AI agents dedicated, scoped keys or a gateway; if you issue keys, add prefixes, show-once and a scanning partnership | Static key count falling month on month; rotation automated for the highest-risk keys |
Practitioner checklist
- Inventory API keys you hold and issue, with owner, purpose, scope, age and last use.
- Replace keys with OAuth, workload identity or federation where the provider supports it.
- Use one key per consumer and environment, never shared across systems.
- Apply API and application restrictions to every key, and set an expiry or review date.
- Store keys in a secrets manager; never in code, images, client apps, IDE settings or logs.
- Send keys in headers, never in URLs.
- Enable push protection and continuous scanning, and monitor provider-side usage and spend.
- Rotate on schedule, on exposure and on staff departure, using overlapping keys.
- Revoke unused and orphaned keys, and confirm revocation in provider logs.
- Give AI agents their own scoped keys or route them through a gateway.
- Maintain and rehearse a leaked-key response procedure.
Standards and references
- OWASP: Top 10 Non-Human Identities Risks 2025
- OWASP: NHI2:2025 Secret Leakage
- OWASP: NHI7:2025 Long-Lived Secrets
- OWASP: API Security Top 10 2023
- OWASP Cheat Sheet Series: Secrets Management Cheat Sheet
- IETF: RFC 9700 Best Current Practice for OAuth 2.0 Security
- Google Cloud: Best practices for managing API keys
- Google Cloud: Manage API keys
- AWS: Usage plans and API keys for REST APIs in API Gateway
- GitHub Docs: Secret scanning partner program
- GitHub Docs: Push protection
- GitHub: Behind GitHub's new authentication token formats
Related NHI Mgmt Group resources: Secrets Management Guide · NHI Authentication Guide · LLMjacking Guide · Secrets Rotation Runbook Template · Top 10 API Security Risks