A refresh token is not a permanent key. It works until the provider, the user or an administrator ends it, and the token endpoint tells you only with an error. Most of those errors mean the user has to sign in again. A few mean nothing about the grant at all, and treating them the same way logs people out for no reason.
This post covers why Google and Microsoft stop honoring a refresh token, how to tell a dead grant from an outage, why two refreshes at once can lose a token, and how Workwae classifies each case and gets the user reconnected without losing the account.
Three kinds of refusal.
OAuth defines invalid_grant as a refresh token that is invalid, expired or revoked,
or that was issued to another client
(RFC 6749 section 5.2). That
is a verdict on the grant: retrying the same token never works. Google and Microsoft both use
it.
invalid_client is a verdict on your app, not the user, so reconnecting does not fix
it. The third kind is no verdict. Microsoft documents temporarily_unavailable as a
server too busy to handle the request, and says to retry
(Microsoft Entra: error codes).
A timeout, a dropped connection or a 5xx belongs here too.
Why Google stops honoring a token.
Google lists the reasons a refresh token can stop working (Google: refresh token expiration):
- The user revoked your app’s access.
- The token has not been used for six months.
- The user changed their password and the token has Gmail scopes.
- The account passed its limit of live refresh tokens.
- The user granted time-based access and it ran out.
-
An administrator set a service your scopes request to Restricted. The error is
admin_policy_enforced. - For Google Cloud scopes, the session length an administrator set was exceeded.
Two of these catch teams in development. A project with an external consent screen in “Testing” gets refresh tokens that expire in 7 days, unless the scopes are only name, email address and profile. Gmail scopes are not. And there is a limit of 100 refresh tokens per Google Account per client id. At the limit, a new token silently invalidates the oldest, so an app that sends a user through consent repeatedly ends its own earlier grants.
Session control fails with invalid_grant too, with an error_subtype
such as invalid_rapt that tells it from a revocation.
Why Microsoft does.
Microsoft’s refresh tokens last 90 days by default, 24 hours for single-page apps (Microsoft Entra: refresh tokens). Every use returns a new one. A user or administrator revoking tokens ends them all. A user’s own password change ends password-based tokens issued to public clients but leaves confidential-client tokens alive, and a server-side app is a confidential client. An administrator’s reset in the Entra or Microsoft 365 admin center ends those too.
The failure carries more detail than Google’s: an error, an
error_description that starts with an AADSTS code, and the same codes in
error_codes
(Microsoft Entra: authorization code flow):
{
"error": "invalid_grant",
"error_description": "AADSTS50173: The provided grant has expired due to it being revoked, a fresh auth token is needed. ...",
"error_codes": [50173]
} The codes that matter for a mailbox (Microsoft Entra: error codes):
AADSTS50173: the grant was revoked. The user may have reset their password.-
AADSTS700082: the refresh token expired from inactivity. AADSTS65001: the user or an administrator has not consented to the app.-
AADSTS50076andAADSTS50079: a change such as a Conditional Access policy now requires multifactor authentication. AADSTS700084: a single-page app’s token reached its fixed lifetime.
A request that needs another authentication step can come back as
interaction_required instead of invalid_grant. Microsoft documents it
for that case, so match on both the error string and the code.
Continuous access evaluation shortens the gap between a change and its effect. Exchange Online and other services subscribe to critical events: an account disabled, a password changed or reset, multifactor authentication enabled, all refresh tokens revoked, or high user risk (Microsoft Entra: continuous access evaluation).
What is not a revoked token.
An outage of the token endpoint says nothing about the grant. Mark an account as needing
reauthorization only on a refusal the provider chose to give. A failed or timed-out
connection, any 5xx, a 429 and temporarily_unavailable get a retry, with a growing
delay and some randomness so accounts that failed together do not retry together.
invalid_client and other request errors need a developer, not the user.
Refresh once per account.
Microsoft does not revoke the old refresh token when it issues a new one. It expects you to
discard the old one and keep the new one
(authorization code flow).
The OAuth spec allows a server to revoke the old token when it issues a new one
(RFC 6749 section 6). On such
a server, two workers that refresh the same token at once race: the second request presents a
token the first just spent, gets invalid_grant, and a healthy account looks
revoked.
So refresh in one place per account, store the new refresh token whenever the response carries one, and write it back only over the value you read. A writer that loses re-reads and uses the winner’s token.
How Workwae handles it.
- When it refreshes. A token is refreshed when less than five minutes of
validity are left. A request the provider rejects with a 401 forces one refresh and one retry,
for Gmail and Graph. Microsoft refreshes always ask for
offline_access, so the response carries a new refresh token. - One refresh at a time. The worker that owns an account holds its token in memory, and mail, calendar, contacts and IMAP logins share it. Concurrent callers share one load. Across processes the credential is stored with a compare-and-swap on the sealed value, up to three attempts. A new refresh token replaces the stored one; with none returned, the old one stays.
- Classification. An unreachable token endpoint, a 5xx, a 429 and
temporarily_unavailableare transient: the account staysactiveand the sync backs off from 30 seconds, doubling to 15 minutes with about 20 percent jitter, never less than the provider’sRetry-After.invalid_clientand any other error string are configuration problems: the account staysactive, is checked again about every 15 minutes, and no event is sent.invalid_grantis a dead grant, and so areinteraction_required,consent_requiredandlogin_required, which arrive asreason: “interaction_required”. - A dead grant. In one transaction the account becomes
reauth_required,statusReasonstatus_reasonis set,account.reauth_requiredis emitted and the workspace’s admins are alerted. Only anactiveaccount makes the move, so it happens once. Its sync stops. - While it waits. Reads of synced data work. Requests that need the provider
answer 409
account_reauth_required.
The event carries email, provider, cloud,
externalRefexternal_ref and a reason, the error code that ended the grant. The
envelope’s accountIdaccount_id names the account. A handler that starts the reconnect:
import { createClient, parseWebhook } from "@workwae/sdk";
const workwae = createClient({ apiKey: process.env.WORKWAE_API_KEY });
export async function handleWebhook(request: Request): Promise<Response> {
const body = await request.text();
// Throws WebhookVerificationError when the signature or the body is wrong.
const event = await parseWebhook(process.env.WORKWAE_WEBHOOK_SECRET!, request.headers, body);
if (event.known && event.type === "account.reauth_required" && event.accountId) {
const { url, expiresAt } = await workwae.connectSessions.create({
redirectUri: "https://app.example.com/mail/connected",
accountId: event.accountId,
state: crypto.randomUUID(),
});
// Yours: tell event.data.externalRef's user to open url before expiresAt.
await sendReconnectLink(event.data.externalRef, url, expiresAt);
}
return new Response(null, { status: 204 });
}import os
import uuid
from datetime import datetime
from fastapi import Request, Response
from workwae import UnknownEvent, Workwae, parse_webhook
workwae = Workwae(api_key=os.environ["WORKWAE_API_KEY"])
async def handle_webhook(request: Request) -> Response:
body = await request.body()
# Raises WebhookVerificationError when the signature or the body is wrong.
event = parse_webhook(os.environ["WORKWAE_WEBHOOK_SECRET"], request.headers, body)
if (
not isinstance(event, UnknownEvent)
and event.type == "account.reauth_required"
and event.account_id
):
session = workwae.connect_sessions.create(
redirect_uri="https://app.example.com/mail/connected",
account_id=event.account_id,
state=str(uuid.uuid4()),
)
# Yours: tell event.data.external_ref's user to open url before expires_at.
send_reconnect_link(event.data.external_ref, session.url, session.expires_at)
return Response(status_code=204)Reconnecting keeps the account:
-
The session signs in to the account’s own provider. A different mailbox signing in
fails with
account_mismatch. -
The connect updates the same account row and its credential in place, so the account id and
its synced data are untouched. The status goes back to
activeand the sync role is woken to claim the account. -
account.connectedis sent withreauthorized: true, so a handler can tell a reconnect from a new account. Shared mailboxes opened with that grant come back too.
Limits.
-
Workwae classifies on the OAuth
errorstring. It does not readerror_description,error_codesor Google’serror_subtype, so a password reset, an inactivity expiry and a missing consent all arrive asreason: “invalid_grant”. The firstinvalid_grantmoves the account; there is no second attempt. -
Nothing warns you before an expiry. Workwae does not check whether a tenant’s own
Google app is in Testing, so its 7-day tokens end as a plain
invalid_grant. -
reauth_requiredclears only through a new grant.PATCHcannot set the status, and fixing a Conditional Access policy does not bring the account back without a reconnect. -
The reconnect needs the user. If Google issues no refresh token on a repeat consent, the
connect fails with
missing_refresh_token. - The SDKs are alpha:
@workwae/sdkis 0.1.0-alpha andworkwaeis 0.1.0a2, so their surface can still change.
The connect guide covers reconnect sessions and every connect error, and account events lists the event payloads. Connect describes the hosted flow for Gmail and Microsoft 365.