Back to BlogTemp Mail Lab Journal

How API Security Works: Authentication, Keys, and Tokens

TempMailLab TeamJuly 27, 20267 min read
API gateway, shield, and key vault representing protected service connections.

A practical guide to API authentication, authorization, keys, access tokens, replay protection, secret storage, and secure server connections.

An API is a promise between software systems: send a request in a known format and receive a controlled response. That promise becomes a security boundary as soon as the request can read records, change settings, move money, or trigger another service.

API security therefore includes more than putting HTTPS on a URL. It covers who can call an endpoint, what that caller may do, how secrets are stored, how keys are exchanged, and how the system notices abuse.

Three responsibilities need separate checks. Authentication establishes who is calling. Authorization decides what that identity may access. Cryptography protects the channel and the data, but it does not decide whether a caller should be allowed to delete an object.

What API security protects

An API handles several kinds of value at once. A request may contain an access token, a user identifier, a payment reference, or data copied from another system. The response may expose private records or operational details. Even endpoint names, error messages, and timing can help someone map the service.

OWASP places broken object-level authorization first in its 2023 API Security Top 10. An endpoint that accepts an object ID must check whether the authenticated caller may use that specific object, not merely whether the token is valid.

The OWASP API Security Top 10 also highlights broken authentication, broken function-level authorization, unrestricted resource consumption, security misconfiguration, and poor API inventory. Treat the list as a prioritization aid, not a substitute for threat modeling.

Record every public and internal endpoint, the data it touches, the authentication method it accepts, and the owner responsible for it. Include machine-to-machine APIs, webhooks, administration routes, third-party integrations, and old versions. A forgotten route is still part of the attack surface.

Authentication is not authorization

Authentication and authorization decisions meeting at a protected API server.

API keys and access tokens are not interchangeable

An API key usually identifies a calling application or integration. An access token represents authorization granted to a client, often with a defined audience, scope, and lifetime. Product labels are inconsistent, so the security design should be based on what the credential can do, not what the dashboard calls it.

For OAuth-based APIs, RFC 9700 provides current security guidance on token privilege restriction, redirect validation, refresh-token protection, and replay prevention. Access tokens should be narrowly scoped and short-lived, while long-lived credentials need stronger storage, rotation, and revocation controls.

A bearer token is a credential that works for whoever presents it. That makes transport protection and storage especially important. A short-lived access token can limit the damage from theft, while a refresh token should be protected more carefully and revoked when a session ends or a device is lost.

Validate the token's issuer, audience, expiry, and signature, and give each integration its own narrowly scoped key. Keep secrets out of browser code, mobile bundles, public repositories, URLs, and query strings. Logs, crash reports, analytics events, and support attachments can leak them too.

Authorization belongs at the point where data or an operation is used. Check object ownership, tenant boundaries, roles, and fields that may be changed. A profile endpoint should not silently accept administrative properties just because the JSON parser accepts them. Return only the fields the caller needs, and make denied operations consistent enough that they do not reveal sensitive existence information.

How API keys should be stored

Encryption is useful when a secret must be recoverable, such as an integration credential that a service must present to a partner. Hashing serves a different purpose. A password verifier should normally be a slow, salted password hash because the server does not need to recover the original password.

An API key may need encryption at rest or a one-way hash, depending on whether the original value must be shown or sent again. Keep keys out of source control and ordinary configuration files. Use a secret manager or hardware-backed key service with narrow read permissions, protected backups, audit records, and a documented recovery path.

For many records, envelope encryption separates the data-encryption key from the key-encryption key that protects it. Store the key identifier and version next to ciphertext so a controlled rotation can decrypt old data and re-encrypt it. Never invent a cipher or hide a secret in reversible encoding. Base64 changes representation; it provides no confidentiality. Rotation needs an overlap plan, client updates, and revocation of the old version. If a secret may have leaked, revoke it immediately and investigate where it appeared.

API key lifecycle from generation and storage through rotation and revocation.

How servers establish secure connections

Two servers need to protect traffic even though they cannot safely send a shared secret in plain text over the network. TLS solves this through an authenticated handshake. In TLS 1.3, the parties negotiate parameters, exchange ephemeral key shares, and derive fresh symmetric session keys. A certificate and a signature help the client authenticate the server; mutual TLS adds a client certificate when the server must authenticate the calling service. The key exchange does not send the session key itself.

Ephemeral Diffie-Hellman exchanges can provide forward secrecy when fresh private values are used. A certificate answers an identity question, not an authorization question, so the application still needs to check whether a service may call a specific endpoint. Trace the secret through every hop, queue, cache, and monitoring system, and choose one-way TLS, mutual TLS, signed requests, or workload identity according to the internal trust model.

How to design safer API requests and responses

Two servers exchanging TLS messages, certificates, and fresh session keys.

Use HTTPS for every environment that carries real credentials, including staging when it contains realistic data. Validate input against an expected schema, limit request size and expensive operations, and set rate limits that reflect the business action rather than only the IP address. Keep errors useful to operators without publishing secrets or stack traces. Redact tokens, cookies, passwords, and personal data before logs leave the service.

When an API calls another API, verify the destination, certificate, authentication, and response shape. Treat third-party responses as untrusted input. Set timeouts, limit redirects, and prevent a user-controlled URL from reaching internal administration services. OWASP calls unsafe consumption of APIs a distinct risk because a dependency's endpoint and validation may not match your own security assumptions.

Signed requests still need replay protection

A valid signature can show that a request was created with an accepted key and that its signed contents were not changed. It does not automatically prove that the request is new. An attacker who captures a valid payment, webhook, or administrative request may try to send the same bytes again. Bind signatures to a timestamp, nonce, request identifier, or other freshness value, then reject requests outside a short time window or identifiers that have already been processed.

Webhook receivers should verify the signature against the exact raw request body before trusting parsed fields. Store processed event IDs long enough to prevent duplicate work, make sensitive operations idempotent where possible, and design signing-secret rotation so old and new keys can overlap briefly without leaving an unlimited fallback. Authentication confirms the sender; replay controls confirm that the same authorized message is not being reused.

Release review checklist

Before releasing an API, check the following:

  • Every endpoint has explicit authentication and authorization decisions, including object-level checks.
  • Keys are scoped, stored outside code, and visible only to services that need them.
  • Revocation, rotation, rollback, and audit records are tested.
  • Sensitive fields stay out of responses, logs, analytics, and error messages.
  • Old routes, debug modes, undocumented webhooks, expensive queries, and large payloads are included in testing.

What encryption and key exchange cannot solve

Encryption cannot fix weak identity proof, a stolen token, an authorization bug, or a service that returns too much data. A perfect handshake can carry an unsafe request perfectly. Strict authorization cannot protect a credential sent over a channel that attackers can read.

API security combines protocol protection, secret lifecycle management, access control, input handling, inventory, and operational response. Each secret should be short-lived and purpose-specific. Each permission should be explicit. Each connection should use a maintained authentication and encryption protocol.

Let TLS and established cryptographic libraries handle key exchange. Store recoverable secrets in a managed key service with rotation and audit controls. When a request reaches a resource, check the caller's authority at that resource. Those boundaries turn a collection of endpoints into a system that can be reviewed, monitored, and repaired.

Primary standards and guidance

OWASP API Security Top 10 2023

NIST key-management guidance

RFC 9700: OAuth 2.0 Security Best Current Practice

RFC 9846: TLS 1.3

CybersecurityOnline Privacy
Donate