How to secure API keys

Topic: Security basics

Summary

Store API keys in a secret manager or env; never in code or public config. Use short-lived tokens where the API supports it; scope keys to the minimum permissions; rotate and revoke when leaked or when no longer needed. Use this when adding or hardening API access.

Intent: How-to

Quick answer

  • Never commit API keys to git or store in plain config. Use a secret manager, env vars at runtime, or a secure config store. Restrict read access to the process that needs the key.
  • Prefer short-lived tokens (OAuth, JWT) over long-lived keys so rotation is automatic. If only long-lived keys exist, scope them to the minimum permissions and rotate on a schedule.
  • If a key is leaked, rotate it immediately and revoke the old one; search logs and git for the key value to see if it was used; notify the API provider if they need to invalidate on their side.

Prerequisites

Steps

  1. Store securely

    Put API keys in a vault or secret manager; inject at runtime via env or config that is not in repo. Do not log or expose keys in error messages or debug output.

  2. Scope and use short-lived when possible

    Create keys with the minimum scope (read-only if that is enough). Prefer OAuth or short-lived tokens so expiry handles rotation; for long-lived keys, set a rotation schedule.

  3. Rotate and revoke

    Rotate keys on a schedule or when someone leaves or a leak is suspected. Create the new key, update consumers, then revoke the old key. Document the process.

  4. Detect leakage

    If a key appears in git or logs, rotate immediately. Use pre-commit hooks or scanning to block commits that look like keys; monitor API provider dashboards for unusual usage.

Summary

Store API keys in a secret manager or env; scope minimally; prefer short-lived tokens. Rotate and revoke on schedule or after a leak; detect and respond if keys appear in git or logs.

Prerequisites

Steps

Step 1: Store securely

Use a vault or secret manager; inject at runtime. Do not commit or log keys.

Step 2: Scope and use short-lived when possible

Grant minimum permissions; prefer short-lived tokens. For long-lived keys, set a rotation schedule.

Step 3: Rotate and revoke

Rotate on schedule or after a leak or offboard. Update consumers, then revoke the old key.

Step 4: Detect leakage

Scan for keys in git and logs; rotate immediately if found. Use hooks and monitoring to reduce risk.

Verification

No keys in code or config in repo; keys are scoped and rotated; leakage would trigger rotation and review.

Troubleshooting

Key in git history — Rotate the key; consider history rewrite or tooling to redact. API has no short-lived option — Rotate long-lived keys on a schedule and scope tightly.

Next steps

Continue to