~/blog/spotify-refresh-token
Published on

Secure Token Rotation — Best Practices

248 words2 min read–––
Views
Authors
  • avatar
    Name
    D3c0d3r
    Twitter
APIs & Tokens

APIs are the backbone of modern systems — and secrets like API keys and refresh tokens are the crown jewels attackers seek. This post gives a short, practical guide to issuing, storing, and rotating tokens securely.

Key Principles

  1. Use short-lived access tokens and a trusted token issuer (STS). Long-lived refresh tokens should be stored encrypted and rotated.
  2. Keep secrets out of the repo: use secrets managers (e.g., Vault, AWS Secrets Manager, Azure Key Vault) for runtime retrieval.
  3. Instrument authentication flows so you can detect abnormal use (e.g., token use from unexpected geolocations).

Rotation pattern (example)

  1. Issue short-lived access tokens (minutes) and refresh tokens (hours/days) when a client authenticates.
  2. On rotation, revoke the previous refresh token server-side and issue a new one.
  3. If a rotation fails multiple times (indicating a stuck client), require re-authentication.

Example: secure refresh flow (high level)

Client -> Authorization Server: authenticate
Authorization Server -> Client: short-lived access token + refresh token
Client -> API: send access token
When access token expires:
  Client -> Authorization Server: present refresh token
  Authorization Server: validate, revoke old refresh token, issue new tokens

Practical checklist

Following these practices reduces blast radius when a secret leaks and increases the organization's ability to recover quickly.