jwtExpired function
Whether the JWT token has expired, or will within skew.
Reads the exp claim from the payload — base64url, with any missing
padding restored — and compares it with the current time plus skew, so
a token about to die is treated as dead and refreshed before a request
carries it, not after the server rejects it.
jwtExpired(token); // 30s of margin
jwtExpired(token, skew: const Duration(minutes: 2)); // more, for slow links
The signature is not checked. This decides when to refresh, which is a client-side convenience — the server still verifies the token. Never use it to decide whether to trust one.
- A malformed token — not three dot-separated parts, a payload that
is not base64url JSON, an
expthat is not a number — counts as expired. Refreshing is the safe answer to a token you cannot read. - A token with no
expclaim never expires, per RFC 7519, and returnsfalse. Treating it as expired would refresh before every request.
now is for tests; it defaults to the current time.
To plug it into AuthConfig.isTokenExpired, see jwtExpiryCheck.
Implementation
bool jwtExpired(
String token, {
Duration skew = const Duration(seconds: 30),
DateTime? now,
}) {
final parts = token.split('.');
if (parts.length != 3 || parts[1].isEmpty) return true;
try {
final payload = utf8.decode(
base64Url.decode(base64Url.normalize(parts[1])),
);
final claims = jsonDecode(payload);
if (claims is! Map) return true;
if (!claims.containsKey('exp')) return false;
final exp = claims['exp'];
if (exp is! num) return true;
// Compared in seconds, as numbers: building a DateTime from a far-future
// `exp` would overflow and read as expired.
final threshold =
(now ?? DateTime.now()).add(skew).millisecondsSinceEpoch / 1000;
return threshold >= exp;
} catch (_) {
return true;
}
}