API Authentication Architecture for Integrations

API Authentication Architecture for Integrations

Authenticate to every vendor differently and you get credentials that are hard to rotate. Decide one auth model — OAuth2, rotation, least-privilege scopes — before the build.

A site or storefront that authenticates to every vendor a different way ends up with credentials that are hard to rotate and outages that are hard to trace. Decide one machine-to-machine api authentication architecture before the first integration: OAuth2 client credentials as the server-to-server default, a managed secret store with zero-downtime rotation, and least-privilege scopes separated per environment. This article gives you a per-vendor auth-model table you fill in during scoping and the small amount of token-handling code that model implies.

Auth is an architecture decision, not a per-call afterthought

The first integration sets the pattern unless someone decides on purpose what that pattern should be. Take a hypothetical project: the payment SDK ships with an API key, so a key goes in an environment variable. The next vendor uses OAuth2, so a token fetch gets written inline next to the call that needed it. A third only offers signed requests, so an HMAC helper appears in a utility file. None of these choices were wrong in isolation. Together they are a maintenance debt: three credential lifecycles, three failure modes, and no single place that answers "what does this site authenticate to, and how."

That debt is invisible until a credential has to change. A vendor forces a key rotation, a secret leaks into a log, or a security review asks where every production credential lives. At that point the absence of one model is not an inconvenience — it is a sequence of small, risky, manually coordinated changes across services that were never designed to rotate. The cost is the same one the broader integration discipline keeps pointing at: a decision deferred until production is more expensive than the same decision made during scoping.

The fix is to treat authentication as one architecture decision applied everywhere, not a per-call afterthought. Two things are decided before the first integration: the auth model the site prefers, and where secrets live and how they rotate. Everything after that is filling in a table, not inventing a pattern. This is machine-to-machine integration auth — how the site and storefront prove identity to vendor APIs. End-user login and single sign-on are a different problem on a different surface, addressed at the website-inventory level of this topic, and are out of scope here.

The common auth shapes

A few auth shapes recur across vendors, and choosing a default for each settles much of the per-integration debate. The default server-to-server pattern is the OAuth2 client-credentials grant, which RFC 6749 defines for a client requesting access to protected resources under its own control, or to those of another resource owner that have been previously arranged with the authorization server, and limits to confidential clients (RFC 6749 §2.1). The application authenticates with its client credentials (RFC 6749 also allows other supported means of authentication; this article's default is a client ID and secret) to obtain an access token whose lifetime the authorization server sets, presents that token as a bearer credential per RFC 6750, and requests a new token before the current one expires. RFC 6749 says the response to this grant should not include a refresh token, so the client repeats the grant rather than refreshing. Short-lived tokens limit the blast radius of a leak: a token captured from a log stops working once it expires. RFC 6750 says token servers should issue short-lived bearer tokens of one hour or less, particularly to clients that run in a web browser or other environments where information leakage may occur. The long-lived client secret, meanwhile, stays in one place that only the token call touches.

API keys are the simplest shape and among the harder ones to contain. A static key is acceptable for low-sensitivity, read-mostly integrations where the vendor offers nothing else and the data is not regulated — a public maps tile key, a status feed. It is not acceptable for anything that moves money or touches personal data, because a static key is a long-lived bearer credential with no built-in expiry. Where a vendor's only option is a key, prefer one that supports signed requests: an HMAC signature over the request body and a timestamp proves possession of a shared secret without putting the secret on the wire, and a replay window makes a captured request short-lived even though the secret is not.

Service accounts and short-lived tokens beat long-lived keys whenever the choice exists. A build pipeline that needs to call a vendor at deploy time should mint a narrowly scoped, short-lived token for that job rather than carry a permanent key. Mutual TLS is the right shape when a vendor requires cryptographic client identity at the transport layer. Sector rules can also call for certificate-based client identity: in EU open banking, for example, the PSD2 regulatory technical standards (Commission Delegated Regulation (EU) 2018/389, Article 34(1)) require payment service providers, when they identify themselves towards the account servicing payment service provider under Article 30(1)(a), to rely on qualified certificates for electronic seals or for website authentication — so check which certificate type a rule names before treating it as an mTLS requirement. RFC 8705 defines how mTLS and OAuth2 combine when both apply. The rule of thumb is consistent: the shorter the credential's life and the narrower its scope, the less a leaked credential can do.

Secret storage and rotation

Where a secret lives is part of the architecture, not an operational detail. Environment variables injected from a managed secret store at deploy time are a reasonable floor for a small surface; a dedicated secret manager with audit logging and per-environment isolation is the better target as the integration inventory grows. The non-negotiables are the same either way: never in source control, never in a client bundle, never in a log line. A secret in a client bundle is not a secret — anything the browser can read, an attacker can read. Integration credentials belong only in code paths that run on infrastructure you control.

Rotation has to be designed, because the naive version causes an outage. Where the vendor allows two valid secrets at once, the zero-downtime pattern is dual-credential overlap: the vendor issues the new secret while the old one is still valid, the application holds both, traffic shifts to the new secret, and only then is the old one revoked. Concretely, the secret store holds a primary and a secondary slot; the token call tries the primary and falls back to the secondary, so there is no instant at which a valid request fails because a rotation was in flight. Without the overlap, rotation is a coordinated, high-risk deploy; with it, rotation is a routine, reversible change.

Rotation cadence is a decision, not a reaction. Set a default interval per credential class — shorter for anything touching money or personal data — and rotate on schedule rather than only after an incident. A scheduled rotation that already works is also your incident response: when a credential leaks, "rotate now" is a button you have already pressed a dozen times, not a procedure you are inventing under pressure.

Least privilege and scope

A credential should be able to do exactly what its integration needs and nothing else. OAuth2 scopes, key permissions, and service-account roles all express the same idea — request orders:read if the integration only reads orders, not a full-access token because it was easier to copy from the quickstart. Over-scoped credentials are the difference between a contained incident and a general one: a leaked read-only catalog token is an annoyance, while a leaked write-everything token is a breach. The OWASP API Security Top 10 (2023 edition, the latest on the project site as of Nov 2026) lists broken object level authorization (API1) and broken authentication (API2) among its top ten API security risks. Over-broad credentials can make either failure reach further, turning one mistake into many.

Separation is the other half of least privilege. Every integration gets its own credential, and every environment gets its own. Per-integration separation means a compromised vendor credential cannot be used to reach a different vendor's data through your application, and revoking one integration's access never collaterally breaks another's. Per-environment separation — strictly distinct sandbox and production secrets — means a sandbox secret is never a production credential, and production secrets have no reason to sit on a developer's machine. These are not extra credentials for their own sake; each boundary is a wall that limits how far a single compromise travels.

Failure and revocation

Auth fails in normal operation, and the system has to absorb it without cascading. The common case is an expired or revoked token: the resource server should respond with a 401, and the client may request a new access token and retry (RFC 6750 §3.1). In the design here, the client requests a new token once, retries the single request, and continues. The anti-pattern is letting that 401 propagate as a generic failure that every caller retries blindly, turning one expired token into a thundering-herd of token requests. The token cache is the boundary that contains this — getting a new token is a single, shared operation behind the cache, not a stampede of concurrent token requests from every in-flight request.

Leaked credentials need a detection-and-response path decided before the leak, not after. The detections are unglamorous and effective: alert on credential use from an unexpected network or region, on a sudden change in call volume or scope, and on any secret appearing in a log or a public repository. The response is the rotation pattern you already built — revoke the compromised credential, promote the standby, and let the dual-credential overlap make the swap a non-event for live traffic. An auth model without a revocation story is a model that works only until the day it matters most. Transport-level resilience — timeouts, bounded retries, and circuit breakers around the token call itself — is a default this topic treats separately; here the point is only that auth failure must degrade gracefully, not collapse.

The auth decision summary

The deliverable is a table you fill in once per integration during scoping, not a pattern you reinvent per vendor. It records the shape, the credential's lifetime, where the secret lives, and what triggers rotation, so the model is something you can reason about instead of excavate from commits.

Integration classDefault authCredential lifetimeWhere the secret livesRotation trigger
Server-to-server vendor APIOAuth2 client credentialsToken short-lived (RFC 6750 recommends one hour or less); client secret long-livedManaged secret store, server-onlyScheduled + on incident
Low-sensitivity read-only feedAPI key, signed if availableLong-lived keySecret store, server-onlyScheduled
Regulated or high-value vendormTLS, or the certificate type the vendor or rule names (+ OAuth2 if required)Certificate lifetimeSecret store / key vaultCertificate expiry + incident
Build or CI jobShort-lived service-account tokenJob durationCI secret store, never persistedPer run (minted fresh)

The code the default model implies is small. A client-credentials integration needs one cached token fetch that requests a new token early and shares a single in-flight request among concurrent callers, written once per direction of trust and never inlined per call site:

typescript
// Client-credentials token cache: fetch once, request a new token before expiry.
// One module per vendor; never inline a token fetch at a call site.
type Token = { value: string; expiresAt: number }
let cached: Token | null = null
let inflight: Promise<string> | null = null // one token request shared by concurrent callers

// Used only when the token response omits expires_in (RFC 6749 §5.1: RECOMMENDED,
// not required). Set it to the default lifetime the vendor documents.
const DEFAULT_LIFETIME_S = 300

// application/x-www-form-urlencoded encoding, as RFC 6749 §2.3.1 specifies for Basic credentials.
const formEncode = (s: string) => new URLSearchParams({ v: s }).toString().slice(2)

async function getAccessToken(): Promise<string> {
  // Renew 60s early to leave a margin for requests sent close to expiry.
  if (cached && cached.expiresAt - 60_000 > Date.now()) return cached.value
  // Concurrent callers wait on the request already in flight instead of each calling the token endpoint.
  if (!inflight) inflight = fetchToken().finally(() => { inflight = null })
  return inflight
}

async function fetchToken(): Promise<string> {
  const now = Date.now()
  // HTTP Basic client authentication: RFC 6749 §2.3.1 says authorization servers MUST support it
  // for clients issued a password; put credentials in the body only if the vendor documents that.
  const id = formEncode(process.env.VENDOR_CLIENT_ID!)
  const secret = formEncode(process.env.VENDOR_CLIENT_SECRET!) // server-only, from secret store
  const res = await fetch(process.env.VENDOR_TOKEN_URL!, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${Buffer.from(`${id}:${secret}`).toString('base64')}`,
    },
    body: new URLSearchParams({
      grant_type: 'client_credentials',
      scope: 'orders:read orders:write', // least privilege, not full access
    }),
  })
  if (!res.ok) throw new Error(`token endpoint ${res.status}`)

  const json = (await res.json()) as { access_token: string; expires_in?: number }
  const lifetimeS = json.expires_in ?? DEFAULT_LIFETIME_S
  cached = { value: json.access_token, expiresAt: now + lifetimeS * 1000 }
  return cached.value
}

That is the whole auth surface for a well-behaved vendor: one model, one secret store, one cached token call, scoped to the minimum and separated per environment. How that token-bearing call survives a slow or failing vendor — timeouts, retry math, idempotency, circuit breakers — is its own decision, treated separately within this topic so it gets the depth it deserves.

Diagnostic checklist for the next planning cycle

  • Pick one default server-to-server auth model — OAuth2 client credentials unless a vendor forces otherwise
  • Choose where secrets live and prove none are in source control or client bundles
  • Where vendors allow two valid secrets at once, design the dual-credential overlap so rotation is a routine change, not an outage
  • Scope every credential to the minimum its integration needs — no full-access tokens copied from quickstarts
  • Separate credentials per integration and strictly per environment, sandbox versus production
  • Write down the per-vendor auth-model table for every integration before any integration code
  • Define the leaked-credential detection signals and the revoke-and-promote response before you need them
Project Inquiry