1. Home
  2. Blog
  3. Amazon Ads API OAuth and Token Management

Data Engineering

Amazon Ads API OAuth and Token Management for Ad Platform Integrations

Amazon Ads API OAuth and token management, plus Google, Meta and TikTok: refresh token lifetimes, encrypted storage, refresh at scale, revocation, audits.

OAuth token management for ad platform APIs means storing each customer's refresh token encrypted, refreshing short-lived access tokens before they expire, and catching revocation before a dashboard goes stale. On the Amazon Ads API, OAuth runs through Login with Amazon: access tokens last 60 minutes, and refresh tokens issued on or after July 30, 2026 expire 365 days after the advertiser's consent. Google Ads, Meta and TikTok each add their own lifetimes and limits.

This is the part of an ad platform integration that nobody demos and everybody depends on. Your product holds refresh tokens that can read, and often change, your customers' Amazon, Google, Meta and TikTok ad accounts. If one leaks, it is a security incident. If one silently expires, the customer notices before you do. Most "pipeline is broken" tickets we see in ad-tech products turn out to be token problems.

This guide is for SaaS and ad-tech backend engineers and security leads. It covers how the major platforms' OAuth implementations differ, how to store tokens, how to run refresh at scale, how to handle revocation and reconnects, how to keep scopes tight, how to audit access per tenant, and what a security review will check.

How each platform's OAuth differs

All four use the OAuth 2.0 authorization code flow defined in RFC 6749, but the details that matter in production differ. Verify these against the current docs; several changed in 2026.

Amazon Ads API OAuth and refresh tokens (Login with Amazon)

  • Grant: the advertiser signs in through a region-specific Login with Amazon URL (North America, Europe or Far East) and your app receives an authorization code, which expires after 5 minutes.
  • Access tokens: valid for 60 minutes.
  • Refresh tokens: a refresh returns a new access token and the same refresh token. Refresh tokens issued on or after July 30, 2026 expire 365 days after the advertiser's consent; older ones have no fixed expiry. They can also be invalidated by revocation, by changes to your LwA credentials, or if Amazon detects suspicious activity.
  • Identity: refresh tokens start with Atzr|, are at most 2,048 bytes and are tied to one client application.

Amazon SP-API

SP-API also uses Login with Amazon, through a separate application. One extra obligation: Amazon requires you to rotate your application's LWA client secret every 180 days. You are notified 90 days ahead, and the old secret stops working seven days after you generate a new one, so the new secret has to reach every service that exchanges tokens within that window.

Google Ads

  • Credentials: OAuth 2.0 plus a developer token on every call. Service accounts are an option for accounts you already manage; customer-facing apps use the multi-user flow.
  • Refresh token failure modes: Google lists several, including the user revoking access, the token going unused for six months, a project in "Testing" publishing status (tokens expire after 7 days), time-limited access granted by the user, and a limit of 100 refresh tokens per Google Account per OAuth client ID, beyond which the oldest token is invalidated without warning.

Meta

Default user access tokens are short-lived (hours); a long-lived user token generally lasts about 60 days. For server-to-server Marketing API access, businesses typically use system users, whose token settings are managed in Business Manager. Check the expiry configured for each token rather than assuming one. A Meta Conversions API access token, generated in Events Manager for server-side event sending, is a separate credential from Marketing API tokens; give it the same storage and logging rules. Our Conversions API setups keep it in the secrets manager with the rest.

TikTok

The TikTok API for Business issues advertiser access through its own authorization flow, separate from TikTok's consumer Login Kit. Read expires_in and any refresh token fields from the actual responses and store them, rather than hardcoding a lifetime.

Storing tokens: encryption, key management, never in logs

Treat refresh tokens like passwords that never expire on their own.

  • Encrypt at rest with envelope encryption. A key management service holds a key-encryption key; each tenant (or tenant group) gets a data key; tokens are encrypted with the data key. Compromising the database alone yields nothing usable. Amazon's SP-API security guidance, for example, requires credentials encrypted at rest with at least AES-128 (AES-256 recommended) in a secure key management system.
  • Keep tokens out of application config. No refresh tokens in environment files, source code or CI variables. Use a secrets manager or an encrypted column with tightly controlled decryption rights.
  • Never log them. Scrub Authorization headers and token fields in your HTTP client, your error tracker and your tracing. Add a log filter that redacts known token prefixes such as Atza| and Atzr|.
  • Encrypt in transit. TLS 1.2 or higher everywhere, including internal hops.
# Example: envelope encryption for a tenant's refresh token (illustrative)
import os, base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def encrypt_token(kms, kek_id, tenant_id, refresh_token: str) -> dict:
    dk = kms.generate_data_key(KeyId=kek_id, KeySpec="AES_256",
                               EncryptionContext={"tenant_id": tenant_id})
    nonce = os.urandom(12)
    ct = AESGCM(dk["Plaintext"]).encrypt(nonce, refresh_token.encode(), tenant_id.encode())
    return {
        "ciphertext": base64.b64encode(ct).decode(),
        "nonce": base64.b64encode(nonce).decode(),
        "encrypted_data_key": base64.b64encode(dk["CiphertextBlob"]).decode(),
        "kek_id": kek_id,
    }

Binding the tenant ID as encryption context and associated data means a token copied into another tenant's row will fail to decrypt.

OAuth token management at scale: refresh flows and expiry

With hundreds of tenants and several platforms, refresh becomes a scheduling problem.

  • Refresh on demand, cache until near expiry. Keep the access token in memory or a short-lived cache and refresh a few minutes before it expires, not on every job.
  • Single-flight per credential. When 20 jobs for one tenant start at once, only one should refresh; the rest wait for the result. Without a lock you multiply token calls and, on platforms that issue new refresh tokens, risk overwriting a valid token with an older one.
  • Store rotated refresh tokens atomically. Amazon returns the same refresh token, but platforms that rotate refresh tokens (as RFC 9700 recommends for some clients) return a new one each time. Save it in the same transaction that records the refresh.
  • Do not re-authorize casually. With Google's 100-token limit per account and client, a support script that reconnects accounts repeatedly can silently invalidate tokens other tenants or environments depend on.
  • Track consent age. For Amazon Ads tokens with a 365-day lifetime, store consented_at and expires_at, and email the customer 30, 14 and 7 days before expiry with a reconnect link.

A minimal credentials table carries tenant, platform, account, encrypted token, key reference, granted scopes, consent date, expiry, last successful refresh, last error and a status (active, needs_reconnect, revoked).

Revocation and the reconnect experience

Customers revoke access, change jobs, remove your app or lose their own permissions. Plan for it:

  • Recognize the error. Amazon returns HTTP 400 with invalid_grant when a refresh token is no longer valid; Google and others return similar errors. Classify these as "needs reconnect", not as transient failures.
  • Stop retrying. Pause that tenant's jobs for that platform immediately. Retrying a revoked token wastes quota and can look like suspicious activity.
  • Tell the customer clearly. An in-app banner and an email naming the platform and account, with a one-click reconnect, resolve most cases in a day.
  • Keep their history. Existing data stays; only new loads pause. After reconnecting, backfill the gap automatically.
  • Honor deletion duties. Platform policies may require deleting data when authorization ends. Amazon's SP-API security guidance, for instance, requires deleting information within 30 days after a customer revokes authorization.

Least-privilege scopes

Request only what the product needs, a principle RFC 9700 states directly for access token privileges.

  • Meta: request ads_read if you only report; add ads_management only for features that write.
  • Amazon Ads: advertising::campaign_management covers most read and write operations, so enforce read-only in your own architecture: reporting services get tokens that are only used for read endpoints, and only the change-applying service can call write endpoints.
  • Google Ads: the Ads scope is broad, so the same internal separation applies. Use the customer's manager account structure to limit which accounts a connection can reach.

Separate services make scopes meaningful: the reporting pipeline should not hold the code path that changes budgets.

Auditing access per tenant

When a customer or auditor asks "who accessed our account data?", you need an answer from records:

  • Log every decryption of a tenant credential: service, job, tenant, time.
  • Log every API call with tenant, platform, operation type (read or write) and outcome, never the token itself.
  • Log every refresh and failure, and alert on anomalies such as refreshes from unexpected services or regions.
  • Review human access quarterly. Who can read the credentials table or the key, and is that still right? Amazon's SP-API guidance requires quarterly access reviews and removing access within 24 hours of a role change.

What a security review checks

A good application security test of an ad integration goes beyond scanning. Expect it to cover:

  • Broken object level authorization (OWASP API1): can tenant A call your API with tenant B's connection ID and pull their data?
  • Broken authentication (API2): session handling around the OAuth callback and your own login.
  • The OAuth flow itself: state parameter validation against CSRF, exact redirect URI matching, PKCE where applicable, and no tokens in URLs or browser storage.
  • Server-side request forgery (API7) and unsafe consumption of APIs (API10): webhooks and callbacks that fetch URLs or trust platform responses blindly.
  • Secrets hygiene: tokens in repositories, logs, crash reports or analytics events.

We test these as part of application security testing. Our security page describes how we handle credentials in our own builds, such as Protego, where 30+ seller accounts are connected and analyzed securely via SP-API.

For the surrounding architecture, see multi-tenant ad data pipelines and Amazon Ads API access, or our ad platform integrations, Amazon Ads API development and ad-tech pages. To review your token handling, book a free 30-minute review.

Frequently asked questions

How long does an Amazon Ads API refresh token last?

Refresh tokens issued on or after July 30, 2026 expire 365 days after the advertiser's consent, while older ones have no fixed expiry. Any of them can be invalidated earlier by revocation, by changes to your Login with Amazon credentials, or if Amazon detects suspicious activity. Store the consent date and expiry with each token, and ask customers to reconnect before it lapses.

Do customers need to reconnect when we rotate our client secret?

It depends on the platform, so test before rotating in production. For SP-API, Amazon requires rotating the LWA client secret every 180 days and gives a seven-day overlap before the old secret stops working; confirm in the current docs how rotation affects existing authorizations. The Amazon Ads API refresh token documentation lists changed or deleted Login with Amazon credentials as a condition that invalidates refresh tokens, so plan Ads API credential changes carefully and confirm the impact with Amazon first.

Should we store access tokens or only refresh tokens?

Persist refresh tokens, encrypted, because they are what keeps the connection alive. Access tokens are short-lived (60 minutes on Amazon Ads), so most systems keep them only in memory or a short-lived cache and refresh as needed. If you do persist access tokens, give them the same encryption and logging rules as refresh tokens.

Can staging and production share customer tokens?

Avoid it. Copying production tokens into staging spreads your most sensitive data into a less protected environment, and on Google Ads repeated authorizations count toward the per-account refresh token limit. Use platform test accounts and internal ad accounts for staging. Where a platform allows only one client per company, as Amazon Ads does, keep staging on test and internal accounts rather than customer connections.

Is the Google Ads API developer token an OAuth token?

No. The developer token identifies your application and is sent with every Google Ads API call, while OAuth credentials identify the user or account that granted access. You have one developer token, but one refresh token per connected Google account. Keep the developer token in your secrets manager too, but outside the per-tenant credentials table.

Sources

Want this built for you?

See how we approach it in ad data for ad-tech & SaaS, or talk to an engineer about your accounts.

Talk to an engineer