Prompt
How do I handle authentication for a SaaS integration with refresh tokens?
Latest observation
Oct 23, 2026
OpenAI APIWeb search: off
For a SaaS integration, the usual pattern is:
1) Use OAuth 2.0 with refresh tokens
- Access token: short-lived, used for API calls.
- Refresh token: longer-lived, used only to get new access tokens.
- Don’t ask users to re-authenticate every time.
2) Store tokens securely
- Encrypt refresh tokens at rest.
- Restrict access to token storage.
- Never log access or refresh tokens.
- If possible, store per-tenant and per-user depending on the SaaS model.
3) Refresh automatically
When an API call returns 401 or the access token is near expiry:
- Use the refresh token to request a new access token.
- Update stored access token and, if the provider rotates it, the new refresh token too.
- Retry the original request once.
4) Handle refresh token rotation
Many providers issue a new refresh token on each refresh.
- Always replace the stored refresh token with the latest one.
- If refresh fails because the token is invalid/expired, mark the connection as broken and prompt the user to reconnect.
5) Plan for expiration and revocation
Refresh tokens can expire or be revoked by:
- user action
- admin policy
- password reset
- SaaS-side security changes
Your app should:
- detect invalid_grant / unauthorized errors
- surface a clear “Reconnect your account” message
- avoid endless retry loops
6) Use least privilege scopes
Only request the scopes you need. This reduces risk if tokens are compromised.
7) Separate auth logic from business logic
A clean flow is:
- API client checks token validity
- Auth service handles refresh
- Job runner / webhook handler retries once after refresh
8) Add concurrency protection
If multiple workers may refresh the same token:
- use a lock or compare-and-swap update
- ensure only one refresh happens at a time
- avoid overwriting newer tokens with older ones
9) Monitor and audit
Track:
- refresh failures
- reconnect events
- token rotation success
- unusual auth error spikes
10) Recommended implementation flow
- User completes OAuth consent.
- Save access token, refresh token, expiry, scopes, tenant/user identifiers.
- Before API calls, check expiry.
- If expired, refresh.
- If refresh succeeds, persist new tokens.
- If refresh fails permanently, disable the integration until reconnected.
Example pseudo-flow
if access_token expired:
lock token record
refresh using refresh_token
if success:
save new access_token, expiry, refresh_token(if returned)
else if invalid_grant:
mark connection disconnected
ask user to reconnect
unlock
call SaaS API with access_token
If you want, I can also provide:
- a Node.js, Python, or Go example,
- a database schema for storing tokens,
- or a multi-tenant auth design for SaaS integrations.
Brands