Join our Newsletter — 33% off our NHI Course
Home› Guides› API Key Management Guide: The Full Lifecycle from…
Guide Secrets Management

API Key Management Guide: The Full Lifecycle from Creation to Retirement

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 24 October 2026 14 min read
On this page

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

SituationAPI key suitable?Better option
Third-party SaaS API that only offers keysYes, with controlsAsk the vendor for OAuth or federation support
Identifying a calling project for quota, billing or analyticsYesCombine with token-based authentication for sensitive data
Service-to-service calls inside your cloudNoWorkload identity, IAM roles, managed identities
CI/CD access to cloud providersNoOIDC workload identity federation
Browser or mobile app calling a sensitive APINo, keys in client code are publicUser-based OAuth with a backend that adds the credential
Partner integrations with sensitive dataRarelyOAuth 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 pathExamplePrimary control
Source code and repository historyA 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 codeTruffle 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 toolsAikido 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 issuerBeyondTrust 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 chatKeys in image layers, debug logs, support tickets and chat messagesLog masking; scanning collaboration tools
URLsKeys passed as query parameters end up in logs and historySend 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 choiceWhy it mattersExample in practice
High entropy with a recognisable prefix and checksumScanners can find keys with few false positivesGitHub 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 onceLimits copies and lets you store only a hashStripe displays a live secret key one time when you create it
Customer-controlled scope, expiry and IP restrictionsCustomers can apply least privilege themselvesRestricted keys and per-key expiry
Last-used time and usage per keyCustomers can find and delete unused keysKey list with last activity
Secret scanning partnershipLeaked keys are reported and can be revoked automaticallyGitHub's partner program sends matches in public repositories and npm packages to a provider endpoint
Stronger alternatives on offerSensitive customers can avoid static keysOAuth 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

SignalSourceResponse
Key pattern in a commit or pushPre-commit hooks, push protection, CI scanningBlock, then rotate if it reached a remote
Key found in public code or packagesProvider partner programmes, public scanningTreat as compromised; revoke immediately
Use from a new IP range, country or user agentProvider usage logsVerify with the owner; restrict or rotate
Spend or volume spikeBilling alerts, quota metricsThrottle, investigate, rotate
Calls to APIs the key has never usedProvider audit logsCheck for scope drift or abuse; add API restrictions
Attempts to use a revoked or expired keyGateway and secrets manager logsFind 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

  1. Revoke or disable the key immediately. Do not wait to rotate gracefully if the exposure is public; automated scanners find public keys quickly.
  2. Issue a replacement and update consumers from the secrets manager, not by pasting the new key around.
  3. Review provider logs for use since the key was exposed, and investigate unfamiliar sources, endpoints and spend.
  4. Remove the key from where it leaked, including repository history and package versions, but assume copies exist.
  5. 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 areaNIST CSF 2.0NIST SP 800-53 Rev. 5ISO/IEC 27001:2022 Annex ACIS Controls v8.1OWASP NHI Top 10
Inventory and ownershipID.AM-02, ID.AM-08CM-8, IA-4A.5.9, A.5.165NHI1
Least privilege and restrictionsPR.AA-05AC-6, AC-3A.5.15, A.8.36NHI5
Secure storage and no embedded keysPR.AA-01, PR.DS-01IA-5(7), SC-28A.5.17, A.8.243, 16NHI2
Expiry and rotationPR.AA-01IA-5A.5.175NHI7
One key per consumer and environmentPR.AA-05IA-4, AC-2A.5.16, A.8.315NHI8, NHI9
Leak detection and usage monitoringDE.CM-03, DE.CM-09SI-4, AU-6A.8.15, A.8.168, 16NHI2
Leaked-key responseRS.MI-01, RS.MI-02IR-4A.5.2617NHI2

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

MetricWhat it showsTarget direction
Keys in inventory with a named owner and purposeAccountabilityUp, towards 100%
Keys older than their rotation periodLong-lived secret exposure (NHI7)Down
Keys without API or application restrictionsBlast radius of a leakDown
Integrations moved from keys to federation or short-lived tokensProgress away from static secretsUp
Secrets blocked at push compared with found after mergeShift-left effectivenessRatio up
Median time from leak detection to revocationResponse speedDown
Keys unused for 90 days or moreDormant attack surfaceDown

See the Identity Security Metrics Guide.

Implementation roadmap

PhaseActionsExit criteria
First 30 daysTurn 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 keyScanning live everywhere; no unrestricted production keys
Days 31 to 90Move 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 alertsAll production keys vaulted and owned; one rehearsal completed
Days 91 to 180Replace 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 partnershipStatic 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

Related NHI Mgmt Group resources: Secrets Management Guide · NHI Authentication Guide · LLMjacking Guide · Secrets Rotation Runbook Template · Top 10 API Security Risks

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 24 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.