ScreenshotNeo

BlogGuides

API Key Permissions and Security: A Practical Guide

Learn how to limit API keys, store and rotate them safely, detect abuse, and protect sensitive endpoints in production.

By the ScreenshotNeo team1 October 20268 min read

API keys are bearer credentials: anyone who obtains one may be able to use the APIs, quotas, data, or billing account attached to it. Secure them by limiting each key to the smallest set of APIs, operations, resources, origins or networks, and time required; storing it outside code and URLs; monitoring every use; and rotating it with an overlap window.

What API key security must achieve

A secure key-management design answers six questions for every credential:

  • Who uses it? Record an owner, application, environment, and business purpose.
  • What can it call? Restrict APIs, methods, scopes, resources, and conditions.
  • Where can it be used? Apply browser-origin, IP, VPC, workload, or device restrictions where supported.
  • How long does it live? Set an expiration or review date and remove dormant keys.
  • How will you detect misuse? Log requests, source locations, methods, errors, quotas, and spend.
  • How quickly can you stop it? Maintain a tested revoke-and-replace procedure.

Google states that publicly exposed keys can cause unexpected charges or unauthorized data access, and that unrestricted API keys are insecure. A standard Google API key also does not authenticate a principal; authorization keys tied to a service account behave more like long-lived access tokens and should not be treated as a safe production default for resource-management APIs.

Choose the right credential model

Model Identity strength Privilege control Lifetime Best use
Unrestricted API key Project or application association only Very coarse Usually long-lived Temporary prototypes only
Restricted API key Project or application association API, operation, origin, IP, or resource restrictions Managed by rotation and review Server integrations that require a provider key
Fine-grained access token User, service, or workload identity Scopes, methods, repositories, resources, and conditions Prefer short expiration APIs supporting granular authorization
IAM or workload identity Strong service or workload identity Policy and resource conditions Short-lived or automatically issued Cloud workloads and internal services
Federated identity External identity provider plus mapped role Policy, claims, and conditions Short-lived session Multi-account or human access

Prefer IAM, federation, or short-lived credentials when the platform supports them. Use an API key when the provider requires one, then compensate with strict API and application restrictions.

Design least-privilege permissions

  1. Inventory the actual calls. List endpoints, HTTP methods, resources, environments, and jobs that need the credential.
  2. Create separate keys. Do not share one key between production, staging, local development, and unrelated services.
  3. Allow only required APIs. Disable every API the application does not call.
  4. Limit operations and resources. A reporting worker may need read access to specific records but not create, update, delete, or administer them.
  5. Add application restrictions. Use server IP ranges, private networks, workload identity, browser origins, or Android/iOS application restrictions as appropriate.
  6. Set an expiry or review date. Short-lived tokens are preferable; long-lived keys need an owner and scheduled review.
  7. Recheck privilege creep. Compare granted permissions with observed calls and remove permissions that are no longer used.
Workload Typical restriction Avoid
Backend service Server-side secret, API restrictions, egress IP or workload identity Embedding the key in frontend JavaScript
CI job Environment-specific secret, narrow scope, short expiry, protected branch rules Printing the key in build logs
Browser or mobile app Provider-supported origin or application restrictions and a proxy for privileged calls Assuming an embedded key is secret
Third-party integration Dedicated key, resource allowlist, quotas, monitoring, and rapid revocation Sharing an employee’s personal token

Store keys safely

  • Use a managed secret manager or encrypted CI/CD secret store.
  • Keep keys out of source code, repositories, issue trackers, chat, screenshots, shell history, and unencrypted files.
  • Prevent commits with secret scanning and pre-commit or server-side repository checks.
  • Load secrets at runtime through environment injection or a secret-manager SDK.
  • Do not put credentials in query strings unless the provider requires that form; URLs are commonly retained by proxies, access logs, analytics systems, and browser history.
  • Redact authorization headers, query parameters, request bodies, and exception messages before sending logs to a central system.

Python: load a key without hard-coding it

import os
import requests

api_key = os.environ["PAYMENTS_API_KEY"]
response = requests.get(
    "https://api.example.com/v1/report",
    headers={"Authorization": f"Bearer {api_key}"},
    timeout=30,
)
response.raise_for_status()
print(response.json())

Node.js: use an injected secret

const apiKey = process.env.PAYMENTS_API_KEY;
if (!apiKey) throw new Error('PAYMENTS_API_KEY is not configured');

const response = await fetch('https://api.example.com/v1/report', {
  headers: { Authorization: `Bearer ${apiKey}` },
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
console.log(await response.json());

Transport and endpoint protection

Use HTTPS and the provider’s approved authentication header or SDK. Validate TLS certificates, set connection and response timeouts, and avoid following redirects to untrusted hosts when credentials could be forwarded. API keys alone should not protect high-value resources: require user or workload identity, authorization checks, input validation, rate limits, and audit logs at the API layer.

For public clients, assume an embedded key can be extracted. Put privileged operations behind your server, issue narrowly restricted public keys where supported, and enforce authorization on every request rather than trusting the presence of a key.

Rotation: overlap, verify, revoke

  1. Create a replacement key with the same or narrower permissions.
  2. Store it in the secret manager under a new version or name.
  3. Deploy consumers so they can use the new key. During the overlap window, accept both keys if the provider and application support it.
  4. Exercise the main workflows and inspect error, quota, and audit logs.
  5. Revoke or delete the predecessor.
  6. Remove dormant copies from CI variables, local files, deployment manifests, and documentation.
  7. Record the rotation date, owner, reason, and next review date.

There is no universal rotation interval. Choose one based on credential lifetime, exposure risk, provider support, and operational cost. Rotate immediately after suspected exposure; do not wait for the normal review.

Monitor use and respond to compromise

Capture a safe audit record containing key identifier or hash, timestamp, caller service, source network, API and method, resource class, status code, latency, quota usage, and estimated spend. Never store the secret itself. Alert on new geographies or networks, unusual methods, volume spikes, repeated authorization failures, quota exhaustion, and unexpected billing.

Breach playbook

  1. Identify the exact key and affected environments.
  2. Revoke it or apply an emergency deny rule.
  3. Issue replacement credentials and rotate dependent secrets if they may have been exposed together.
  4. Inspect logs for unauthorized reads, writes, configuration changes, and billing impact.
  5. Notify owners and affected parties according to your incident process.
  6. Fix the exposure path, add a regression check, and document the timeline.

cURL example with safe shell handling

curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer ${PAYMENTS_API_KEY}" \
  --connect-timeout 10 --max-time 30 \
  https://api.example.com/v1/report

Do not paste the expanded command into a ticket or shared terminal transcript. Prefer a secret-injection mechanism that masks the variable in CI logs.

Or skip the browser setup

When your application needs website screenshots, ScreenshotNeo provides a single API request instead of maintaining a browser, cookie handling, popup cleanup, and rendering infrastructure. Treat its access key as a bearer credential: keep it in a server-side secret manager, restrict the calling service, and avoid exposing it in client code or logs. The endpoint accepts the key as the access_key query parameter, so apply URL-redaction rules in every proxy and logging layer.

See the ScreenshotNeo API documentation for the available options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests; r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90); open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' }); const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie banners, newsletter popups, and chat widgets are removed before the shot.
  • Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers identify the page verdict and billing result.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
  • Every plan includes the features; 1,000 screenshots per month are free with no card, and paid plans start at $5 for 3,000 shots.

Create a free ScreenshotNeo account with 1,000 screenshots per month and no card.

Performance, reliability, and cost

  • Performance: Narrow permissions reduce policy evaluation and blast radius. Cache only non-sensitive responses, set explicit timeouts, and use bounded retries with exponential backoff for transient 429 and 5xx responses.
  • Reliability: Keep a tested replacement path, monitor provider status and quotas, and fail closed when a credential is missing or invalid. Never silently fall back to an unrestricted key.
  • Cost: Least privilege limits unauthorized usage and surprise charges. Set provider budgets and quotas, alert before limits, and attribute spend to a key, service, and environment.
  • Retries: Retry idempotent reads selectively. Use idempotency keys for supported writes and avoid retrying authentication failures until credentials are fixed.

Troubleshooting

Symptom Likely cause Fix
401 or 403 Wrong key, expired token, missing scope, or API restriction Check the secret version, required permission, resource policy, clock, and caller identity; issue a replacement if needed.
Requests work locally but fail in production Production secret is absent or source IP/origin is not allowlisted Verify deployment injection and update the application restriction for the production network.
Unexpected charges or quota exhaustion Leaked or unrestricted key Revoke immediately, inspect audit logs, create a restricted replacement, and add spend alerts.
Key appears in logs URL, exception, proxy, or debug logging captured it Rotate the key, purge accessible logs where possible, add redaction, and use approved headers or SDK auth.
Rotation causes an outage Old key revoked before all consumers switched Use overlap-and-replace, verify every consumer, then revoke the predecessor.
429 responses Rate or quota limit reached Throttle callers, use bounded exponential backoff, request an appropriate quota, and investigate anomalous traffic.

Security checklist

  • Every key has an owner, purpose, environment, allowed APIs, restrictions, and review date.
  • Production keys are separate from development and test keys.
  • Permissions are limited to required APIs, methods, resources, and conditions.
  • Secrets are stored in a managed secret store or encrypted CI/CD secret.
  • Source control and logs use secret scanning and redaction.
  • Credentials travel over HTTPS using approved authentication mechanisms.
  • Usage, errors, quotas, source locations, and spend are monitored.
  • Rotation and emergency revocation have been exercised.
  • High-value operations require authorization beyond possession of an API key.

FAQ

How often should API keys be rotated?

Use the shortest lifetime your provider and deployment process can support. Review long-lived keys on a scheduled basis and rotate immediately after suspected exposure; there is no single safe interval for every system.

Are API keys enough to protect sensitive endpoints?

No. They identify possession of a credential, not necessarily a person or workload. Add IAM or user authentication, authorization checks, network controls, rate limits, validation, and auditing for sensitive operations.

Should an API key be sent in a URL?

Only when the provider requires it. URLs may be logged or retained by intermediaries. If a query parameter is unavoidable, redact it at every logging layer and keep the request server-side.

What should I do with an unused key?

Delete or revoke it. An unused credential still creates an unnecessary path to unauthorized use and makes inventory and incident response harder.

Can one key serve several applications?

A dedicated key per application and environment gives clearer audit trails, smaller blast radius, and safer rotation. Share only when the provider’s restrictions and operational requirements make separation impractical.

Primary guidance: Google Cloud API key best practices, GitHub credential security, OWASP Authorization Cheat Sheet, and OWASP REST Security Cheat Sheet.